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?
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; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With