我在我的控制器中注入EventHubClient,如下所示

services.AddScoped<EventHubClient>(a =>
     {
        eventHubClientIncomplete = EventHubClient.CreateFromConnectionString(new EventHubsConnectionStringBuilder(eventHubSettingsIncompleteApplications.ConnectionString)
        {
           EntityPath = eventHubSettingsIncompleteApplications.EventHubName
        }.ToString());
        return eventHubClientIncomplete;
     });


一切正常。但是现在我需要从不同的端点发送到多个EventHub。我该怎么做...任何指针?

最佳答案

我想到了3个解决方案:

1.为EventHubClient创建自己的工厂。然后在服务中添加工厂。这样,您将能够在需要时注入工厂实例,然后从工厂方法中获取通缉EventHubClient

2.使用其他DI引擎。例如:Unity容器,您可以通过它获得以下服务:container.Resolve<IService>(key)

3.创建一个用于保存EventHubClient的类。

    public class EventHubClientHolder
    {
        public string Name;
        public EventHubClient eventHubClient;
    }


    public void ConfigureServices(IServiceCollection services)
    {
        services.AddControllersWithViews();
        services.AddSingleton<EventHubClientHolder>(_ => { return new EventHubClientHolder() { Name = "A", eventHubClient = ..... }; });
        services.AddSingleton<EventHubClientHolder>(_ => { return new EventHubClientHolder() { Name = "B", eventHubClient = ..... }; });
    }


    public HomeController(ILogger<HomeController> logger, IEnumerable<EventHubClientHolder> services)
    {
        _logger = logger;
        _services = services;
    }


    public IActionResult Index()
    {
        var eventHubClient = _services.First(_ => _.Name.Equals("A"))).eventHubClient;
        return View();
    }

关于c# - 如何从.NetCore 2.2中的StartUp注入(inject)2 EventHubClient,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59260088/

10-10 17:14