How to register an instantiated object as IOptions in .NET Core

66 Views Asked by At

I have a consul server and I am using its key/value functionality to centralize my configuration. so, I have a key value like this:

"appSetting": {
    "secret": "my-secret",
    "clientKey" : "my-key",
    "apiVersion" : "V2"
}

I will read this configuration by this code snippet and fill it into a object with type of AppSetting:

 var appSetting = new AppSetting();
 var queryResult = await _client.KV.Get(configKey);

 if (queryResult.StatusCode == HttpStatusCode.OK)
 {
      var jsonValue = Encoding.UTF8.GetString(queryResult.Response.Value);
      appSetting = JsonSerializer.Deserialize<T>(jsonValue);
 }

And then I want to register this variable as IOptions into my DI container like this:

services.Configure<AppSettings>(settings =>
    {
        settings = appSettings
     });

but it does not work and my IOptions is empty in my consumer classes.

I am sure that I am reading the setting correctly from the consul.

How can I resolve this issue?

2

There are 2 best solutions below

0
Qing Guo On BEST ANSWER

Try to use Options.Create :

Creates a wrapper around an instance of TOptions to return itself as an IOptions.

services.AddSingleton(serviceProvider =>
{
    return Options.Create(appSetting);
});

result:

enter image description here

0
Navid_pdp11 On

the answer that is provided by @Qing Guo is the most generic solution but also, there is another way only when we are using the Consul as config manager in our solutions. and that is using the Winton.Extensions.Configuration.Consul to register Consul as a configuration provider for our application.

builder.Configuration.AddConsul("MyApp/appsettings", source =>
{
    source.ConsulConfigurationOptions = configuration =>
    {
        configuration.Address = new Uri(builder.Configuration["consulConStr"]);
    };
    source.ReloadOnChange = true;
});