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

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

问题描述

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

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

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

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天全站免登陆