【发布时间】:2019-09-25 19:13:22
【问题描述】:
我正在将 .NET Core 2.x 控制台应用程序设置为 Windows 服务,并且需要根据环境加载 appsettings json 文件。我正在考虑使用标识环境的命令行参数启动服务。我如何在 Visual Studio 中做到这一点?无论我在项目设置中设置什么,EnvironmentName 值始终为“Production”。
如何从命令行参数设置我的环境?
var hostBuilder = new HostBuilder()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddCommandLine(args);
config.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: false, reloadOnChange: true);
config.AddEnvironmentVariables();
})
.ConfigureServices((hostContext, services) =>
{
//Inject additional services as needed
services.AddHostedService<JobRunner>();
});
【问题讨论】:
-
对于 .net 5.0,请参阅 docs.microsoft.com/en-us/aspnet/core/fundamentals/host/… 它讨论了 IHostEnvironment 设置 EnvironmentName 如何由通用主机构建器确定。注意前缀是如何用于环境变量提供者的。