With ASP.NET Core the Microsoft team also introduced the Options pattern, which allows to have strong typed options and once configured the ability to inject the options into your services.
First we start with a strong typed class, which will hold our configuration.
public class MySettings
{
public string Value1 { get; set; }
public string Value2 { get; set; }
}
And an entry in the appsettings.json
.
{
"mysettings" : {
"value1": "Hello",
"value2": "World"
}
}
Next we initialize it in the Startup class. There are two ways to do this
Load it directly from the appsettings.json
"mysettings" section
services.Configure<MySettings>(Configuration.GetSection("mysettings"));
Do it manually
services.Configure<MySettings>(new MySettings
{
Value1 = "Hello",
Value2 = Configuration["mysettings:value2"]
});
Each hierarchy level of the appsettings.json
is separated by a :
. Since value2
is a property of the mysettings
object, we access it via mysettings:value2
.
Finally we can inject the options into our services, using the IOptions<T>
interface
public class MyService : IMyService
{
private readonly MySettings settings;
public MyService(IOptions<MySettings> mysettings)
{
this.settings = mySettings.Value;
}
}
If the IOptions<T>
isn't configured during the startup, injecting IOptions<T>
will inject the default instance of T
class.