https://codingblast.com/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. 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. Another way to get values from our Configuration: Now this means that we can use 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: 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 For reloading configuration functionality to work, there are two things you need to have: If you don’t fancy using After this, you can use ASP.NET Core Configuration – Reloading, Binding, Injecting
Introduction
Binding to models – strongly typed configuration options
Injecting configuration to our code
IOptions<MessagesOptions>
anywhere in our application.IOptions
interface has only one member:Binding the appsettings.json
IOptions<CbnSettings>
inside of our code.Reloading configuration
IOptionsSnapshot
instead of IOptions
IOptionsSnapshot<CbnSettings>
in your code (you find it ugly or whatever is the reason), you can do this:CbnSettings settings
in your constructor.