【发布时间】:2018-11-26 15:54:08
【问题描述】:
我在 .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。在这种情况下如何实现相同的注册?
【问题讨论】:
-
刚刚意识到它是主机生成器而不是 Web。检查一下。
-
我知道你想做的事。我无法理解的是您想在哪里执行此操作。
-
查看
HostBuilderthe source,提供者是在创建主机之前构建的最后一件事。到目前为止,没有看到太多可用于执行您所描述的扩展点。也许如果你解释一下你想要这个环境配置的确切位置,我们也许可以看看它是否真的可行。 -
@Nkosi 我似乎找到了一个可行的答案。我已经在下面发布了。我想它也回答了你关于我想在哪里做这个的问题。
标签: c# dependency-injection .net-core .net-core-2.1 ambientcontext