Using Microsoft.Extension.Configuration with dotnet core console project

2018-01-05

Problem

Lately I have created the small console application. Because, I have used dotnet core and I need to add some persistent configuration. Because, web.config is no longer existing by default in new framework, I have used the new Microsoft.Extension.Configuraiton classes. This set of assemblies allow to use and mix difference source for configuration. Now you can store some configuration in xml, ini or json and then merge it with environmental variables.

Solution

My solution was to load Microsoft.Extension.Configuration with Microsoft.Extension.Configuration.CommandLine and Microsoft.Extension.Configuration Microsoft.Extensions.Configuration.Json NuGets to allow me to load configuration and pass it from command line.

Because I am using MS Extension library I can be config source agnostic, that is I can plan to use json configuration file but test it by passing configuration from command line.

Output of build

To start with using, you need to create ConfigurationBuilder

After that you can configure it with any method required: After that you need to finalize it by building;

Benefits

The results is IConfigurationRoot object. This object allows you to access contant in two ways

For example configuration file:
The value of alpha can be access by using test:alpha key or getting alpha key from test section.
The value of alpha can be access by using test:alpha key or getting alpha key from test section.


Blog comments powered by Disqus