简体   繁体   中英

How to Inject 2 EventHubClient from StartUp in .NetCore 2.2

I am injecting EventHubClient in my Controller like below

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

It's working fine. But now i have a requirement to send to multiple EventHubs from different endpoints.. How do i do that...any pointers?

I thought of 3 solutions:

1.Create your own factory for EventHubClient . Then add the factory in services. In this way you will be able to inject the factory instance when needed, and then get wanted EventHubClient from factory method.

2.Use other DI engine. For example: Unity Container, with which you can get service as following: container.Resolve<IService>(key)

3.Create a class for holding 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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM