ASP.NET Core Configuration – Reloading, Binding, Injecting


In the last post, we talked about ASP.NET Core Configuration in general.

We saw how is it set up by default from ASP.NET Core.

We also talked about sources and that order matters.

This time we will talk about mapping configuration to classes.

We will also talk about various ways of injecting configuration settings to our application code.

Another useful thing is automatic reload of configuration. We will see how we can have our configuration reloaded while our application is running.

You can find the code with examples here.


Binding to models – strongly typed configuration options

Let’s say we have following object in our appsettings.json file:

And that we want to get those values and map them to an object.

We would first create a class that matches that structure (or matches only those keys we want to bind):

Now I can bind that object from JSON (section) to an instance of MessageOptions class.

We can also bind it by using Bind method a bit differently:

This is really cool and we could even make a singleton service so we are able to use these values in our code.

However, there is support for this baked in Configuration framework. Read on.


Injecting configuration to our code

Another way to get values from our Configuration:

Now this means that we can use IOptions<MessagesOptions> anywhere in our application.

IOptions interface has only one member:

That means that Value will be an object of a class that we provided, in our case that is MessagesOptions.

I will make a simple Razor Page demonstrating usage of IOptions:

Binding the appsettings.json

Another thing we can do is to make a class that will match appsettings.json root object, not only parts of it. Meaning, all values from appsettings.json that have matching property within the class will map to those properties.

Let’s say we have the following appsettings.json:

And we wanna map “MainMessage” root value and “Messages” object and we are not interested in other keys.

We would have a class like this:

Now we can simply do map Configuration to CbnSettings:

This will enable usage of IOptions<CbnSettings> inside of our code.


Reloading configuration

For reloading configuration functionality to work, there are two things you need to have:

  1. Reload changes enabled on your source (this is enabled by default for appsettings.json by ASP.NET Core host)
  2. Using IOptionsSnapshot instead of IOptions

If you don’t fancy using IOptionsSnapshot<CbnSettings> in your code (you find it ugly or whatever is the reason), you can do this:

After this, you can use CbnSettings settings in your constructor.

Whatever you decide on your project, I would just recommend to be consistent.

Ibrahim Šuta

Software Consultant interested and specialising in ASP.NET Core, C#, JavaScript, Angular, React.js.