This one was also giving me troubles. I don't want to have switches within my code and want to rule it from the outside. And that is possible. There are a lot of options what you see in the posts above. This is what I did.
Setup code
In Program.cs add this
var _configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables()
.Build();
The forth sentence is for environmental settings in json.
The fifth sentence is for overruling in staging and prod by using environment variables.
Then add three files:
- appsettings.json
- appsettings.Development.json
- appsettings.Staging.json
- appsettings.Production.json
In appsettings.json I place the generic values for every environment. IE the name of the application.
In appsettings.Development.json I place the connection string.
You can also do that in Staging and Production. I did that different for security reasons.
Tip
The setup above can run your environment in dev-mode.
In launchsettings.json you can change the ASPNETCORE_ENVIRONMENT to ie Staging to see how it works in test/staging mode.
Deployment
When I deploy to docker I overrule the environment setting to get the code running in the right environment. That is this way (this is is how pass from Nomad environment variables to docker, docker-compose will have a different format, but idea is the same):
env {
ASPNETCORE_ENVIRONMENT = "Staging"
CONNECTIONSTRINGS__MYCS = "MyConnectionString"
}
When you work this way, you have clean code.