Using strongly typed configuration in .NET Core console app


Imagine you write a console application and you need to read the configuration from the configuration file, in the strongly typed way.

.NET core comes to help us with it. It's usually demonstrated in ASP.NET Core MVC  but it's also possible to use it in the console application. Let's see.

Show me it!

Let's create two configuration classes which will be used to hold the application and the module name.

 

The application configuration file will look like the following:

 

At the end, let's use it in the application.

 
All the magic (binding) is done through "Bind" method.
 

Don't forget to add the required dependencies. The project.json should contain the following:

 

Once you run it, the result will be:

consoleapp-output

 

Using the strongly typed configuration classes in .NET Core app is easy!

 

Comments (5)

  1. osman pirci says:

    I think you missed to add some content

  2. Dusk says:

    Hi! Nice article! I had a question – So how do I get settings from a different class? Will I have to pass the settings class object to all the classes I call?

  3. Ivan says:

    Thanks, works perfectly.
    Now, how to save changed settings back to the appsettings.json configuration file ?

  4. Thierry Prost says:

    Are annotations possible for the configuration classes?

  5. LoudRock says:

    For future readers..I think the Dotnet Core 2.1 syntax sugar is:

    MyModuleSettings moduleSettings = new MyModuleSettings();
    builder.Bind(“SectionA”, moduleSettings);

Skip to main content