Vaughan Reid's blog

ASP.NET Core with IOptions

One of my favorite improvements when moving to ASP.NET Core applications is that configuration feels like a first class citizen in the infrastructure. Previously I often had to do some manual work in the DI registration to create configuration objects that could be injected into my classes. No longer!

ASP.NET Core uses the options pattern out of the box which I think is a clean and flexible way to inject your configuration. Its simple and powerful at the same time.

So how does it work. First you define a json representation of your class in your appsettings.json file. Such as:


"Person": {
    "Name": "Joe Soap"
}

And create the corresponding POCO class.


public class Person
{
     public String Name { get; set; }
}

Then to use it you register it in the ConfigureServices method of your Startup class. A simple way using defaults would be:


services.Configure<Person>(Configuration);

At this point its ready to inject into your service constructor. You are given 3 Options classes that you could use depending on your situation.

  1. IOptions<Person> This uses the configuration at startup and is registered as a singleton.
  2. IOptionsSnapshot<Person> This is registered as a scope service and will reload the configuration for each request.
  3. IOptionsMonitor<Person> This is a singleton instance that gives you a listener you can use to get any changes to the configuration.

With these 3 service options you can decide how to inject your configuration depending how you expect the configuration to change.