What is the use case of IOptions versus IConfiguration (other than IOptions allows mapping to object)?

Viewed 843

I can inject the IConfiguration config into constructor and then access the app settings from json file via config["settignName"];

Example code inside service class:

public MyService(IConfiguration config)
        {
            _key = config["MyKey"];
        }

I came across IOptions which allows to map app settings from json file to a .net object.

Example:

public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<MySettings>(Configuration.GetSection("MySettings"));
...
}

And then inject the IOption into the constructor.

What is the use case of IOptions versus IConfiguration (other than IOptions allows mapping to object)? I don't see IConfiguration being used in online examples so is that OK to be used or should I switch to IOption?

1 Answers

As explained in documentation sometimes you prefer to split your settings by groups or scenarios, this is really easy with IOptions.

services.Configure<AppSettings1>(configuration.GetSection("AppSettings1"));
services.Configure<AppSettings2>(configuration.GetSection("AppSettings2"));

And then you can specify in your class constructor which one you need. You can have something similar with IConfiguration but you need write more code.

Other reason, I prefer access to the configs values using properties rather than using indexes. If I need to update a config key it will more painful using indexes.

Related