我可以构建2个IServiceProvider并且它们一起工作(.net核心)

时间:2017-08-21 08:12:50

标签: c# dependency-injection asp.net-core .net-core

    IServiceCollection serviceConfiguration = ConfigureServices();       
    IServiceProvider serviceProvider = serviceConfiguration.BuildServiceProvider();
    IBusControl busControl = CreateServiceBus(serviceProvider);

    IServiceCollection services = new ServiceCollection();
    services.AddSingleton<IBusControl>(busControl);      
    IServiceProvider serviceBus = services.BuildServiceProvider();

是否有可能这样做,我需要它,因为CreateServiceBus使用第一个IServiceProvider,它通过依赖注入使用它为什么我需要2个IServiceProvider因为在此之后我想要注册busControl作为IBusControl

1 个答案:

答案 0 :(得分:2)

您可以创建工厂方法并在Startup.cs中加热。

services.AddSingleton<IBusControl>(provider => CreateServiceBus(provider));

然后在Configure方法

中“加热”它
public void Configure(IAppBuilder app, IBusControl bus)
{
}

public void Configure(IAppBuilder app, IBusControl bus)
{
    app.Services.GetRequriedService<IBusControl>();
}