Access IServiceProvider when using generic IHostBuilder

时间秒杀一切 提交于 2019-12-24 10:38:24

问题


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


来源:https://stackoverflow.com/questions/53484777/access-iserviceprovider-when-using-generic-ihostbuilder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!