configuration from scratch in .net core

Ivory Wolf
2 min readAug 16, 2020

--

Adding configuration to a .net core console application.

Following on from:

Here is how to add configuration to a .net core console application. Gone are the old app.config files used for so long. Json files are now used, in particular appsettings.json. Along with the new file type and structure we have access to a lot more patterns and features that help us write better code.

Add an appsettings.json file to a console application — be sure to set it to ‘copy to output’ — and add the following content to the file.

{
"ApiConfiguration" :
{
"Enabled" : "true",
"Timeout" : 5000
},
"ApiKeys" :
{
"Key" : "acfd2acb4ef"
}
}

Adding the Code

Dependencies

Microsoft.Extensions.Configuration
Microsoft.Extensions.Configuration.Json (adds AddJsonFile extension method)
Microsoft.Extensions.Configuration.Binder (adds Bind to extension method)

There are two simple patterns demonstrated here:

The first simply extracts the configuration value by key, the flattened hierarchy of the json into a variable — timeout.

The second is a more formal pattern of binding an object to a configuration section. The ApiConfiguration class has properties that match the ApiConfiguration section. As long as it has a parameter-less constructor we can use the Bind() method to bind the configuration section to and instance of the ApiConfiguration class.

get the source code

--

--

Ivory Wolf
Ivory Wolf

No responses yet