使用通用IHostBuilder时访问IServiceProvider [英] Access IServiceProvider when using generic IHostBuilder

查看:265
本文介绍了使用通用IHostBuilder时访问IServiceProvider的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

之前,使用 IWebHostBuilder ,我有 Configure()方法可以让我做到这一点:

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.)

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

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?

推荐答案

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

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

这篇关于使用通用IHostBuilder时访问IServiceProvider的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆