[英]How to Inject 2 EventHubClient from StartUp in .NetCore 2.2
I am injecting EventHubClient in my Controller like below我在我的控制器中注入 EventHubClient,如下所示
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?但是现在我需要从不同的端点发送到多个 EventHubs .. 我该怎么做...有任何指针吗?
I thought of 3 solutions:我想到了3个解决方案:
1.Create your own factory for EventHubClient
. 1.为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.通过这种方式,您将能够在需要时注入工厂实例,然后从工厂方法中获取想要的EventHubClient
。
2.Use other DI engine. 2.使用其他DI引擎。 For example: Unity Container, with which you can get service as following: container.Resolve<IService>(key)
例如:Unity Container,通过它你可以获得如下服务: container.Resolve<IService>(key)
3.Create a class for holding EventHubClient
. 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.