Strongly typed configuration in ASP.NET Core 2.0 using IOptions<T>

When it comes to configuration, ASP.NET Core provides various ways to read configuration like from a json file, environment variables, command line arguments etc. This is great but it gets better. ASP.NET Core allows you to have a strongly typed configuration and it is the recommended way of reading configuration.

How can you do it?

The way to do it is to have a class with similar structure as a section of your configuration.  Let’s say that you have a configuration like below in your appsettings.json file:


Note: I am using appsettings.json as an example but the configuration can come from any source.


Normally, if you want to read the value of FirstSetting in your code you'll have to access it like Configuration["MyConfigSettings:FirstSetting"] and this is okay for simple configuration but as your application grows and things get more complex this code starts to look cumbersome.

There are a couple of things which I don’t like about accessing the configuration like that but the most important thing which jumps out is that anyone can easily mistype the configuration key and then spend hours wondering why the configuration isn’t getting loaded.

This is where IOptions<T> shines. You can create a class (like below) in which the property names matches the name of the config settings and then bind a section of your configuration to that class in Startup.cs

And then in ConfigureServices method of your Startup.cs:

Now when your app starts, ASP.NET Core framework will bind the entire MyConfigSettings section to your class and will be available throughout your application via DI (Dependency Injection).

Accessing IOptions<T>:

Let’s say you want to access the value in a controller. First, you’ll need to add a reference to Microsoft.Extensions.Options and then in the constructor of your controller you can just receive a property of type IOptions<MyConfigSettings> and store it in some local field/property. The IOptions<T> exposes a property called Value which is of type T and hence contains all the properties of your class with values populated by the configuration system. So the FirstSetting can be accessed like MyConfigSettings.Value.FirstSetting. Here is the complete code for the controller:

This was a pretty simple example but even if you have a more complex type having complex properties that can also be accessed in a similar way given that your configuration values follow the same structure.


Having a strongly typed configuration system really helps in the development process as you don’t have to remember the names of the configuration keys and also saves you from making mistakes. ASP.NET Core provides a nice and easy way to handle this. I hope this post helps you in setting it up in your application.

The complete source code can be found here.


More Resources: