In my Program.cs Main method, I would like to read user secrets, configure a logger and then build the 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();
}
I can get to the configuration by building my own, but I quickly end up in a mess trying to access hosting environment properties:
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();
}
Is there an easier way to access IHostingEnvironment before building the WebHost?
In the
mainmethod, you cannot get theIHostingEnvironmentinstance before building the WebHost, as hosting is not yet created. And you cannot create a new valid instance properly, as it must be initialized using WebHostOptions`.For application name you may use
Assembly.GetEntryAssembly()?.GetName().NameFor environment name use what you currently do (I assume something like this is used in your IsDevelopment() method):
See, methods like
IHostingEnvironment.IsDevelopment()are extension methods that simply do string comparison internally:Note regarding
AddJsonFile: as file name is sensitive in Unix OS, sometimes it's better to use$"appsettings.{envName.ToLower()}.json"instead of.