[英]How to Inject 2 EventHubClient from StartUp in .NetCore 2.2
我在我的控制器中注入 EventHubClient,如下所示
services.AddScoped<EventHubClient>(a =>
{
eventHubClientIncomplete = EventHubClient.CreateFromConnectionString(new EventHubsConnectionStringBuilder(eventHubSettingsIncompleteApplications.ConnectionString)
{
EntityPath = eventHubSettingsIncompleteApplications.EventHubName
}.ToString());
return eventHubClientIncomplete;
});
它工作正常。 但是现在我需要从不同的端点发送到多个 EventHubs .. 我该怎么做...有任何指针吗?
我想到了3个解决方案:
1.为EventHubClient
创建自己的工厂。 然后在服务中添加工厂。 通过这种方式,您将能够在需要时注入工厂实例,然后从工厂方法中获取想要的EventHubClient
。
2.使用其他DI引擎。 例如:Unity Container,通过它你可以获得如下服务: 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();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.