Imran K
Imran K

Reputation: 25

Setup appsettings.json with transformation in Console Application of .net framework(4.8) and Reading in POCO Models

I have a .net framework based Solution which is having Console Application as the Entry point along with multiple dependent Class Library projects. Console Application provides XML based configuration file: App.Config for managing config keys.

What I am looking for implementation similar to .NET5+/Core wherein appsettings.<environment>.json can be used for managing the config keys and values can be defined as per the respective environments. Since this kind of implementation is not provided out of the box in .net framework, I was looking for a hybrid implementation.

This is a solution I found that uses ConfigurationBuilder() class of Microsoft.Extensions.Configuration; and works as expected.

I am beating head to find clean implementation on the transformation(debug/release/uat) part. Identifying the environment should be done via a global variable or is there a way to use Configuration Manager to indicate the builder which file to be used.

Upvotes: 1

Views: 175

Answers (1)

Zarepheth
Zarepheth

Reputation: 2603

My team has things working with code like this:

var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json", optional: false, reloadOnChange: false);
builder.AddJsonFile($"appsettings.{environment}.json", optional: true, reloadOnChange: false);
Configuration = builder.Build()

environment could come from an environment variable or a setting in the app's app.config file. We use the latter approach, since some of our apps use features that require the old, XML style config files.

Upvotes: 1

Related Questions