We need to read from multiple appsettings based on local or not. We achieved this by adding appsettings.local.json.
But we see that although we add this file and set up necessary configurations, we were not able to read config data from appsettings.local.json, all time it saw appsettings.json.
Let me tell by code:
public static void Main(string[] args)
{
var config = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json")
.AddJsonFile("appsettings.local.json", optional: true)
.AddEnvironmentVariables()
.AddCommandLine(args)
.Build();
CreateWebHostBuilder(args, config).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args, IConfiguration config)
{
var webHostBuilder = WebHost.CreateDefaultBuilder(args)
.UseApplicationInsights()
.ConfigureServices(services => services.AddSingleton<IConfiguration>(config))
.UseStartup<Startup>();
return webHostBuilder;
}
In CreateWebHostBuilder, if we do not add .ConfigureServices(services => services.AddSingleton<IConfiguration>(config)) we could not read data from appsettings.local.json. After adding this, we can read from appsettings.local.json. So my question is what happened in here? Can someone provide a reasonable explanation?