使用通用 IHostBuilder 时访问 IServiceProvider

Tim*_*imo 5 c# dependency-injection ambientcontext .net-core .net-core-2.1

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

    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();
    }
}
Run Code Online (Sandbox Code Playgroud)

之前,使用IWebHostBuilder,我有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
    // ...
}
Run Code Online (Sandbox Code Playgroud)

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

使用通用主机构建器,我们似乎永远无法访问构建的IServiceProviderIApplicationBuilder. 在这种情况下如何实现相同的注册?

Tim*_*imo 5

RunConsoleAsync()显然,我们可以拆分该方法所执行的简单步骤,而不是调用扩展,从而允许我们在构建和启动之间执行某些操作:

        await hostBuilder
            .UseConsoleLifetime()
            .Build()
            .AddAmbientThingy(options => options.AddSubscriber(thingy))
            .RunAsync();
Run Code Online (Sandbox Code Playgroud)