I am working on .NET Core 5 Console App and I was trying load appsettings.[environment].json at runtime based on the "ASPNETCORE_ENVIRONMENT = Development" which I setup in debug under project properties.
In the BuildConfig method I can see that
Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
is returning the " Development " text correctly and also loading the 2 file (appsettings.json, appsettings.development.json).
but when I pass the config to different class via constructor and then inspecting config in that class I seeing the (appsettings.json, appsettings.production.json) file not the development file why?
I don't have appsettings.production.json file in my project yet.
static void Main(string[] args)
{
try
{
//setting for SeriLog
var builder = new ConfigurationBuilder();
BuildConfig(builder);
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.ReadFrom.Configuration(builder.Build())
.Enrich.FromLogContext()
.WriteTo.Console()
.WriteTo.File(@"Log\Log.txt")
.CreateLogger();
Log.Logger.Information("Application Starting");
var host = Host.CreateDefaultBuilder()
.ConfigureServices((context, services) =>
{
services.AddTransient<IRIUProcess, RIUProcess>();
})
.UseSerilog()
.Build();
var svc = ActivatorUtilities.CreateInstance<RIUProcess>(host.Services);
svc.Run(args);
}
catch (Exception ex)
{
Log.Logger.Error(ex.ToString());
}
}
static void BuildConfig(IConfigurationBuilder builder)
{
builder.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();
}
Configuration builder return self instance configurated like entityframework core
//setting for SeriLog
var builder = new ConfigurationBuilder();
BuildConfig(builder);
should be
//setting for SeriLog
var builder = new ConfigurationBuilder();
builder = BuildConfig(builder);
Without that, your configuration builder remain unchanged. Adapt also the BuildConfig method for that.
Then you can remove the CreateDefaultBuilder (with use default AspNetCore Configuration) and directly use your instance of configuration:
new HostBuilder().ConfigureHostConfiguration(a => a.AddConfiguration(builder.Build()))
You will have then your host with the same configuration for SeriLog and your host
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.