ASP.NET Core: why using IOptions adapter?

Viewed 298

I have a custom options block (MyOptions) in the appsettings.json configuration file like this:

{
    "ConnectionStrings": {
        "test": "..."
    },
    "MyOptions": {
        "Prop1": "Value1",
        "Prop2": "Value2"
    }
}

My POCO looks like this:

public class MyOptions
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

In Startup, I register it as shown below:

public void ConfigureServices(IServiceCollection services)
{
   var configSection = Configuration.GetSection("MyOptions");
   services.Configure<MyOptions>(configSection);
}

My controller requests it by using the adapter 'IOptions':

public IndexController(IOptions<MyOptions> options)
{
    // ...
} 

Here is my question: why must I use the adapter IOptions? The official documentation says that IOptions is a singleton. Is there some benefit using IOptions instead register the Options as a service like this?

public void ConfigureServices(IServiceCollection services)
{
   var configSection = Configuration.GetSection("MyOptions");
   var option = configSection.Get<MyOptions>();
   services.AddSingleton(option);
}

public IndexController(MyOptions options) // <- Request it without the IOptions adapter
{
    // ...
} 
0 Answers
Related