Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read appsettings.json into object that has an interface defined

I need to read custom settings from appsettings.json into a POCO object that has a custom interface defined. This code works - but is there a better way to do this? Maybe something similar to reading the options via services.Configure and IOptions? Unfortunately, using IOptions is not possible since I am calling another library that expects an object that implements an 'IConfigOptions' interface.

services.AddSingleton<IConfigOptions>(obj => new ConfigOptions        
{
   Param1 = Configuration["Options:Param1"],
   Param2 = Configuration["Options:Param2"],
   Param3 = Configuration["Options:Param3"],
   <etc>
});

Suggestions?

like image 245
argentntx Avatar asked Oct 19 '25 03:10

argentntx


1 Answers

There is methode in Configuration in C# which automatically reads all the property for you from the appsettings.

If the properties of the object match with the names in the JSON, then you can do the following:

services.AddSingleton<IConfigOptions,ConfigOptions>(_ =>
              Configuration
                  .GetSection(nameof(ConfigOptions))
                  .Get<ConfigOptions>());

The appsettings.json looks like:

  "ConfigOptions": {
      "Param1": "text1",
      "Param2": "text2",
      "Param3": "text3"
  }

The ConfigOptions looks like this:

public class ConfigOptions {
     public string Param1 { get; set; }
     public string Param2 { get; set; }
     public string Param3 { get; set; }
}
like image 150
Oscar Veldman Avatar answered Oct 21 '25 17:10

Oscar Veldman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!