In addition to @Kahbazi answer I would like to update my answer like this
In your case You can use Options pattern in ASP.NET Core
Example you have appsetting.json that have structure like this
"Development": {
"Url": "some string"
},
"Stage": {
"Url": "some string"
},
"Prod": {
"Url": "some string"
}
I will need to define a model class like this to store information
public class Development
{
public string Url{ get; set; }
}
So we have the the config structure. The last thing we need is register inside Startup.cs
:
services.Configure<Development>(configuration.GetSection("Development"));
So you can use like this:
private readonly IOptions<Development> _webAppUrl;
public EmailSender(IOptions<Development> _webAppUrl)
{
_webAppUrl = _webAppUrl;
}
_webAppUrl.Value.Url;
This is how Microsoft setup multiple appsetting.json
files. You can take a look at because it's kinda long post
Here is how I config using json file base on environment:
public Startup(
IConfiguration configuration,
IHostingEnvironment hostingEnvironment)
{
_configuration = configuration;
_hostingEnvironment = hostingEnvironment;
var builder = new ConfigurationBuilder();
if (_hostingEnvironment.IsDevelopment())
{
builder.AddUserSecrets<Startup>();
}
else
{
builder
.SetBasePath(hostingEnvironment.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{hostingEnvironment.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
}
}