When do we need IOptions?

Money Sets You Free

I am learning DI in .Net Core and I do not get the idea about the benefit of using IOptions.

Why do we need IOptions if we can do without it?

With IOptions

interface IService
{
    void Print(string str);
}

class Service : IService
{
    readonly ServiceOption options;
    public Service(IOptions<ServiceOption> options) => this.options = options.Value;
    void Print(string str) => Console.WriteLine($"{str} with color : {options.Color}");
}

class ServiceOption
{
    public bool Color { get; set; }
} 

class Program
{
    static void Main()
    {
        using (ServiceProvider sp = RegisterServices())
        {
            //
        }
    }


    static ServiceProvider RegisterServices()
    {
        IServiceCollection isc = new ServiceCollection();

        isc.Configure<ServiceOption>(_ => _.Color = true);
        isc.AddTransient<IService, Service>();
        return isc.BuildServiceProvider();
    }
}

Without IOptions

interface IService
{
    void Print(string str);
}

class Service : IService
{
    readonly ServiceOption options;
    public Service(ServiceOption options) => this.options = options;
    public void Print(string str) => Console.WriteLine($"{str} with color : {options.Color}");
}

class ServiceOption
{
    public bool Color { get; set; }
}

class Program
{
    static void Main()
    {
        using (ServiceProvider sp = RegisterServices())
        {
            //
        }
    }

    static ServiceProvider RegisterServices()
    {
        IServiceCollection isc = new ServiceCollection();

        isc.AddSingleton(_ => new ServiceOption { Color = true });
        isc.AddTransient<IService, Service>();
        return isc.BuildServiceProvider();
    }
}
Manoj Choudhari

In .Net core, it is recommended that all your configurations should be strongly typed based on their use cases. This will help you to achieve separate of concerns.

Practically, you can achieve the same thing without using IOptions as you stated. So, if I go back one step and if we have a look at all the available options in .net core configuration:

1. Raw Configuration[path:key]

You can directly access IConfiguration instance and provide path of JSON key in the accessor part, and the configuration value would be returned.

This is not good approach because there is no strong typing here while reading the configuration.

2. IOptions binding to a Config Section

You can use IOptions implementation (which you already know). This is better because you can have a single class with all related configurations. The IOptions interface provides you additional benefits.

As far as I understood, this IOptions interface decouples your configuration from the actors who are reading the configuration and thereby you can use some additional services from .net core framework.

Please refer MSDN article for details about the benefits.

You can also refer to the twitter conversation at this blog. In that blog, Rick also explains that he could not find any practical case on how this approach is different from the 3rd approach below - as generally the configurations are not dynamic and they are done only once before the application startup.

3. Configuration.Bind() to bind to a Config Section

You can use .Bind call to bind a configuration section to a POCO class. You get strongly typed object. Here if multiple actors are using the configurations, they will not get additional services provided by IOptions interface.

I know this is not exactly pointing out the difference. But I am sure this will bring little more clarity on deciding your preference.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

when do we not need activation function?

When do we need `-e` for sed?

When do we need data classes?

When do we need to define variables in loops?

When do we practically need 'explicit xvalues'?

When do we need generics <> notation?

When do we need to clear the scanf buffer?

Do we still need onSaveInstanceState() when we have ViewModels?

Why do we even need assembler when we have compiler?

Why do we need AppBarLayout when we are using CollapsingToolbarLayout?

When we use linq do we ever need to use from?

Why do we need services when we have components?

Do we need a VPN?

When do we need to run a Java application in a container?

Do we need to synchronize access to an array when the array variable is volatile?

CrossRider - when do we need to use appAPI.JSON?

When is setsid() useful, or why do we need to group processes in Linux?

When and how do we need to use 'undefined' as a value?

Why do we need the "new" keyword when creating an array?

In objective c, when creating objects, why do we need to use *?

When do we need curly braces around shell variables?

When do we need to use --track command in git

When and why do we need ApplicationRunner and Runner interface?

When do we need to create our own custom dependency property?

Do we need synchronization when setting the value of an element in an ArrayList

Why do we need to use a sigmoid function when using backpropagation?

Why and when do we need to flatten JSON objects?

Do we need webhook when our server is interacting with dialogflow?

Why do we need a usbkbd driver when there is usbhid?