Anuj
Anuj

Reputation: 633

Passing user defined object to IoptionsMonitor

I have a working code like below where my business logic is consuming configuration like -

public MyBusinessLogic(MyConfiguration _myConfiguration)
{
   // using _myConfiguration
}

configuration is passed through startup.cs like

public override void ConfigureServices(IServiceCollection services)
{
    base.ConfigureServices(services);

    var **myConfiguration** = new MyConfiguration();
    Configuration.GetSection(nameof(MyConfiguration )).Bind(myConfiguration);
    myConfiguration.value1= "123";
    myConfiguration.value2= "456";
    services.AddSingleton(myConfiguration);
}

Now I want to use myConfiguration using IOptionsMonitor for autoreload feature. Something like -

public MyBusinessLogic(IOptionsMonitor<MyConfiguration> _myConfiguration)
{
   // using _myConfiguration.CurrentValue
}

We can pass generic object(which is created/injected by asp.net) like-

// Add realtime configuration support
services.Configure<MyConfiguration>(Configuration.GetSection("MyConfiguration"));

So my question is how to pass the user-defined object i.e. myConfiguration to IoptionsMonitor and whether it is possible or not?

Upvotes: 1

Views: 1035

Answers (1)

Jcl
Jcl

Reputation: 28272

You can configure it without binding it to IConfiguration:

services.Configure<MyConfiguration>(myCfg => {
  /* here myCfg is an already created instance of `MyConfiguration`, you can set its properties or do whatever, e.g: */
  myCfg.Property1 = myConfiguration.Property1;
  myCfg.Property2 = myConfiguration.Property2;
 
});

And you'll receive the object in the IOptionsMonitor<MyConfiguration>.CurrentValue.

Notice that you don't get any kind of detection change there (it can be implemented but that's way outside the scope of this question), so I'd rather use IOptions and not IOptionsMonitor.

Upvotes: 2

Related Questions