ASP.NET Core 2.0 Configuration

Problem

How to read configuration settings from various sources and use them throughout your application.

Solution

Starting from the Empty Project from a previous post, add appsettings.json and appsettings.Development.json files in your project:

Then read configuration settings in the constructor for Startup class:

Then add option services in ConfigureServicees() method of Startup class:

Finally inject settings as IOptions interface, where T is your POCO:

Running the sample application give you following output:

Configuration-Output

Discussion

ASP.NET Core has a simple mechanism to read application settings from various sources like JSON file, Environment variables or even custom data sources. It is also simple to use the settings, thanks to Dependency Injection.

Although it seems like magic (how did your settings got loaded!) ASP.NET Core 2.0 hides the adding of configuration settings behind CreateDefaultBuilder() method of WebHost, in Program.cs. IConfiguration is then added to the service container and is available in rest of your application, we used this in Startup to add options. To see this, replace the BuildWebHost() method in Program.cs and run the program, you’ll get the same result:

In the solution above two JSON file sources are provided. The important thing to remember is that these sources are read sequentially and overwrite settings from previous source. You could see this in the solution above, the output shows SettingB’s value coming from first settings file whereas the other settings are being overwritten by the second settings file.

Note that a public static property holds IConfiguration instance so that it can be used throughout the application like:

However, a better approach exists to read the settings i.e. to read the settings into a typed POCO class and then inject it as dependency into middleware, controllers etc. In the solution above I’ve used the middleware from a previous post to demonstrate this pattern.

You can also have POCO classes for various sections in the settings file and read them using GetSection() method on IConfiguration:

It’s also possible to populate the settings in code using overload of IServiceCollection.Configure that accepts strongly typed lambda:

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Asp.Configuration

Leave a Reply