在我的Program.cs
主要方法中,我想讀取user secrets,配置一個記錄器,然後構建WebHost
。在構建WebHost之前訪問宿主環境
public static Main(string[] args)
{
string instrumentationKey = null; // read from UserSecrets
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.ApplicationInsightsEvents(instrumentationKey)
.CreateLogger();
BuildWebHost(args).Run();
}
我可以去配置通過建設自己的,但我很快就結束了亂七八糟試圖訪問託管環境屬性:
public static Main(string[] args)
{
var envName = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production";
var configBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{envName}.json", optional: true, reloadOnChange: true);
// Add user secrets if env.IsDevelopment().
// Normally this convenience IsDevelopment method would be available
// from HostingEnvironmentExtensions I'm using a private method here.
if (IsDevelopment(envName))
{
string assemblyName = "<I would like the hosting environment here too>"; // e.g env.ApplicationName
var appAssembly = Assembly.Load(new AssemblyName(assemblyName));
if (appAssembly != null)
{
configBuilder.AddUserSecrets(appAssembly, optional: true); // finally, user secrets \o/
}
}
var config = configBuilder.Build();
string instrumentationKey = config["MySecretFromUserSecretsIfDevEnv"];
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.ApplicationInsightsEvents(instrumentationKey) // that.. escallated quickly
.CreateLogger();
// webHostBuilder.UseConfiguration(config) later on..
BuildWebHost(args, config).Run();
}
是否有訪問IHostingEnvironment
一個更簡單的方法在構建WebHost
之前?
Thanks @Set。我已經使用了這個版本來獲取bootstraping與用戶祕密的工作,但我只是想知道是否有另一種重新設計過程的方式更容易。配置主機的新方法非常好,因此我認爲將其拆毀並讓自己的方法執行主機擴展方法所做的相同的事情是一種恥辱。感謝'envName.ToLower()'提示。 – leon