Access IServiceProvider when using generic IHostBu

2019-07-29 12:58发布

问题:

I'm using IHostBuilder in a .NET Core 2.1 console application. Main looks like this:

    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();
    }
}

Before, with IWebHostBuilder, I had the Configure() method that let me do this:

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
    // ...
}

This allowed me to register something ambient (using the Ambient Context pattern), not part of the application's main dependency graph. (As you can see, I still use the container to instantiate it, which is certainly preferable to newing it up manually. We could see it as a secondary, ambient dependency graph.)

With the generic host builder, we never seem to get access to the built IServiceProvider or the IApplicationBuilder. How do I achieve the same registration in this case?

回答1:

Apparently, instead of calling the RunConsoleAsync() extension, we can split up the simple steps that that method takes, allowing us to do something between building and starting:

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