visit
We lived like this until the test team joined us and deployed in a testing environment. The appsettings.json configuration file in this environment was different. Therefore, we faced another chore - fixing the configuration file manually. At this stage, the human factor intervened; sometimes, we forgot to edit the file, which led to errors and loss of time.
When we got tired of it, we decided to call DevOps to help. However, it still took time. Therefore I came up with an idea and implemented a quick solution for handling multiple environments. Here are the details:There is no default nesting in console applications. Therefore, open the .csproj project file and add:
<ItemGroup>
<Content Include="appsettings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<Content Include="appsettings.Dev.json;appsettings.Testing.json;">
<DependentUpon>appsettings.json</DependentUpon>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
It looks much better, right? Afterward, I attach files with the name of the development environment that appeared in the appsettings.json file:
The appsettings.{Environment}.json contains parts of the config that change relative to the environment. For example, we change the name of the topics for Kafka in the load testing loop:
{
"Kafka": {
"EventMainTopicTitle": "Test_EventMain",
"EventDelayTopicTitle": "Test_EventDelay",
"EventRejectTopicTitle": "Test_EventReject"
}
}
Now, we just need to select the suitable appsettings.json file during the start of the service. To do this, let's make changes to the program class:
/// <summary>
/// Service configuration
/// </summary>
private static IServiceProvider ConfigureServices ()
{
const string environmentVariableName = "ASPNETCORE_ENVIRONMENT";
var environmentName =
Environment.GetEnvironmentVariable (environmentVariable name);
var services = new ServiceCollection ();
_configuration = new ConfigurationBuilder ()
.SetBasePath (Directory.GetParent (AppContext.BaseDirectory) .FullName)
.AddJsonFile ("appsettings.json")
.AddJsonFile ($ "appsettings. {EnvironmentName} .json")
.AddEnvironmentVariables ()
.Build();
services.AddSingleton (_configuration);
services.AddSingleton <KafkaHandler> ();
return services.BuildServiceProvider ();
}
# Create image
# build docker. -t consoleapp
# Run container on Dev
# docker run -d --env ASPNETCORE_ENVIRONMENT = Dev --name app consoleapp
Thanks for your attention and happy coding!
GitHub project: