Adding configuration to a .net core console application.
Following on from:
.net core from scratch — ioc
Tutorial example to show how to add and use the ioc container that comes with .net core and asp.net core in a console…
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.
"Enabled" : "true",
"Timeout" : 5000
}, "ApiKeys" :
"Key" : "acfd2acb4ef"
Adding the Code
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.