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:
Using the strongly typed configuration classes in .NET Core app is easy!
Comments
- Anonymous
March 02, 2017
I think you missed to add some content - Anonymous
March 24, 2017
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? - Anonymous
September 26, 2017
Thanks, works perfectly.Now, how to save changed settings back to the appsettings.json configuration file ? - Anonymous
December 20, 2017
Are annotations possible for the configuration classes? - Anonymous
November 15, 2018
For future readers..I think the Dotnet Core 2.1 syntax sugar is: MyModuleSettings moduleSettings = new MyModuleSettings(); builder.Bind("SectionA", moduleSettings);- Anonymous
December 23, 2018
Thanks, this worked for me
- Anonymous
- Anonymous
February 25, 2019
How do I use HostBuilder.ConfigureAppConfiguration to do the same instead of ConfigurationBuilder?