使用通用 IHostBuilder 时访问 IServiceProvider
Access IServiceProvider when using generic IHostBuilder
我在 .NET Core 2.1 控制台应用程序中使用 IHostBuilder
。主要看起来像这样:
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()
方法让我这样做:
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
// ...
}
这让我可以注册环境(使用环境上下文模式),而不是应用程序主要依赖关系图的一部分。 (如您所见,我仍然使用容器来实例化它,这当然比手动更新它更可取。我们可以将其视为辅助的环境依赖关系图。)
使用通用主机构建器,我们似乎永远无法访问内置的 IServiceProvider
或 IApplicationBuilder
。在这种情况下如何实现相同的注册?
显然,我们可以拆分该方法执行的简单步骤,而不是调用 RunConsoleAsync()
扩展,从而允许我们在 构建和启动之间做一些事情:
await hostBuilder
.UseConsoleLifetime()
.Build()
.AddAmbientThingy(options => options.AddSubscriber(thingy))
.RunAsync();
我在 .NET Core 2.1 控制台应用程序中使用 IHostBuilder
。主要看起来像这样:
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()
方法让我这样做:
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
// ...
}
这让我可以注册环境(使用环境上下文模式),而不是应用程序主要依赖关系图的一部分。 (如您所见,我仍然使用容器来实例化它,这当然比手动更新它更可取。我们可以将其视为辅助的环境依赖关系图。)
使用通用主机构建器,我们似乎永远无法访问内置的 IServiceProvider
或 IApplicationBuilder
。在这种情况下如何实现相同的注册?
显然,我们可以拆分该方法执行的简单步骤,而不是调用 RunConsoleAsync()
扩展,从而允许我们在 构建和启动之间做一些事情:
await hostBuilder
.UseConsoleLifetime()
.Build()
.AddAmbientThingy(options => options.AddSubscriber(thingy))
.RunAsync();