I extended this scenario in order to manage also (optional) User Secrets (from package: Microsoft.Extensions.Configuration.UserSecrets
):
IConfiguration configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory()) // Directory where the json files are located
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddUserSecrets(Assembly.GetEntryAssembly(),optional:true);
.Build();
The order of adding Json Files and User Secrets is important here. See Calling AddJsonFile and AddUserSecrets
I fully agree this is not the preferred way (instead use IOptions<>
and Dependency Injection
and let the application configure the library). But I am mentioning this because I was working on an (very old) library which was reading from app.config (xml). This library can't be configured from the application, instead the library does it directly (expecting values in app.config). This library is used for Full Framework, .NET Core and .NET5 (or newer) applications now. So I had to support appsettings.json as well. It was not really possible to adapt the library in a way so that the application can provide the necessary configuration values to the library. Because of that I added support for JSON to it (for the time being - maybe later on we can spend more effort to make it configureable from the application)
Finally I also support environments and my code looks like this:
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: false);
var environment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
if (!string.IsNullOrEmpty(environment))
{
builder = builder.AddJsonFile(string.Format("appsettings.{0}.json", environment), optional: true, reloadOnChange: false);
if (string.Equals(environment, "Development", StringComparison.CurrentCultureIgnoreCase))
{
builder = builder.AddUserSecrets(Assembly.GetEntryAssembly(),optional:true);
}
}
Note that I decided to manage User Secrets only for Development scope.