【发布时间】:2020-04-14 23:08:20
【问题描述】:
我们有旧版应用程序,我们计划在未来某个时间过渡到 ASP.NET Core API (v2.2)。 为了使它更容易,我们决定开始使用具有所有可用功能的通用主机,用于所有未来的增强(appsettings/logging/DI 等)。 这个想法是,一旦我们切换到 API,我们将复制主机配置,并且大部分代码将继续工作。我们将 host.Services.GetService() 暴露给遗留代码库,它将用作简单的 ServiceLocator。
问题是:使用这种方法有什么缺点吗?另外,我们需要在通用主机上使用 Start/Stop/Run 吗?根据我所阅读的内容,这仅在运行我们不打算使用的 IHostedService 时需要。我测试了它是否在不调用 Start/Stop 的情况下工作,一切似乎都很好,但我发现的所有示例都调用了 Start/Stop,即使没有 IHostedService。
private IHost _host;
private PricingHost()
{
_host = new HostBuilder()
.UseEnvironment("BETA")
.ConfigureAppConfiguration((hostContext, configApp) =>
{
configApp.SetBasePath(System.IO.Directory.GetCurrentDirectory());
configApp.AddJsonFile("appsettings.json", optional: true);
configApp.AddJsonFile(
$"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json",
optional: true);
})
.ConfigureLogging((hostContext, configLogging) =>
{
configLogging.AddConfiguration(hostContext.Configuration.GetSection("Logging"));
configLogging.AddDebug();
configLogging.AddConsole();
configLogging.AddCustomLogger();
})
.ConfigureServices((hostContext, configServices) =>
{
var startup = new Startup(hostContext.Configuration);
startup.ConfigureServices(configServices);
})
.Build();
}
public T GetService<T>()
{
return _host.Services.GetService<T>();
}
public T GetRequiredService<T>()
{
return _host.Services.GetRequiredService<T>();
}
更新:让我试着澄清一下。我们有 10 年历史的传统 Windows 服务。我们计划在未来某个时候将其转换为 asp.net .net core api,但目前仍在进行 Windows 服务的工作。为了简化未来的过渡,我们希望将通用主机用于 DI、配置访问、日志记录等。我们只是想将其用作服务定位器(因此不需要 IHostedService),但在未来一段时间内能够只需复制所有配置/设置并将其粘贴到新 API 中
在进行小型 POC 之后,我知道这是完全可能的,但我想弄清楚是否有任何我应该注意的陷阱以及如何在没有 IHostedService 的情况下正确使用 GenericHost(我需要调用 Run/在某个时候开始/停止,还是没有必要)?
更新:添加我正在做的 dot net fiddle 示例here
【问题讨论】:
-
对不起,我想我没有得到你的问题。您想使用通用主机将 API 从 2.2 迁移到 3.1,对吗? Have you read this documentation。您不一定要使用
IHostedService,但我认为在其他所有情况下,使用 API 是完全有意义的 :) -
@Martin 很抱歉不清楚。问题实际上是关于在没有 IHostedService 的情况下使用 GenericHost 的正确方法是什么(我是否需要调用 Run/Start/Stop/etc. 或执行其他任何操作)以及在使用 GenericHost 作为时我应该注意的任何问题ServiceLocator 通过将 host.Services.GetService
() 暴露给遗留代码库。我更新了我的问题。