使用通用IHostBuilder时访问IServiceProvider

时间:2018-11-26 15:54:08

标签: c# dependency-injection .net-core .net-core-2.1 ambientcontext

我在.NET Core 2.1控制台应用程序中使用IHostBuilder。主要看起来像这样:

    public static async Task Main(string[] args)
    {
        var hostBuilder = new HostBuilder()
            .UseServiceProviderFactory(new AutofacServiceProviderFactory())
            .ConfigureServices(services =>
            {
                // Register dependencies
                // ...

                // Add the hosted service containing the application flow
                services.AddHostedService<RoomService>();
            });

        await hostBuilder.RunConsoleAsync();
    }
}

之前,我使用IWebHostBuilder的{​​{1}}方法可以做到这一点:

Configure()

这使我可以注册一些周围环境的东西(使用环境上下文模式),而不是应用程序的主要依赖关系图的一部分。 (如您所见,我仍然使用容器来实例化它,这肯定比手动更新它更可取。我们可以将其视为辅助的,环境依赖性图。)

使用通用主机生成器,我们似乎永远无法访问已构建的public void Configure(IApplicationBuilder applicationBuilder, IHostingEnvironment environment) { // Resolve something unrelated to the primary dependency graph var thingy = applicationBuilder.ApplicationServices.GetRequiredService<Thingy>(); // Register it with the ambient context applicationBuilder.AddAmbientThingy(options => options.AddSubscriber(thingy)); // Use MVC or whatever // ... } IServiceProvider。在这种情况下如何实现相同的注册?

1 个答案:

答案 0 :(得分:1)

显然,我们无需拆分RunConsoleAsync()扩展名,而是可以拆分该方法执行的简单步骤,从而允许我们在构建和开始之间进行 的操作:

        await hostBuilder
            .UseConsoleLifetime()
            .Build()
            .AddAmbientThingy(options => options.AddSubscriber(thingy))
            .RunAsync();