Looking for a way to initialize IOptions<T> manually?
Background
Ok … I know what you are thinking you must have thought that DotNet Core’s dependency injection handles it for you and we just need to register the configuration class then what is the need for manual initialization? And I completely agree with you but sometimes you may need to create an instance of a class that is dependent on IOptions<T>
dependency (take an example of Unit test cases) and then the real struggle starts.
Let’s say we have ValueController.cs
and it’s accepting one parameter of type IOptions<AppSettings>
.
public class ValueController : Controller
{
public ValueController(IOptions<AppSettings> options)
{
}
}
Also, we have some app configuration in appsettings.json
file.
{
“AppSettings”: {
“SettingOne”: “ValueOne”
}
}
Issue
If you try to pass an instance of AppSettings class to ValueController then DotNet core will not allow it.
var settings = new AppSettings { SettingOne = “ValueOne” };
var obj = new ValueController(settings);
Even it will not allow you to explicitly cast the instance to IOptions<AppSettings>
type. Take a look at the below code which will not work. The below code will throw a runtime exception.
var settings = (IOptions<AppSettings>) new AppSettings { SettingOne = “ValueOne” };
var obj = new ValueController(settings);
Then how do get it fixed?
Solution
Luckily DotNet core provides a static method to create an object of IOptions<T>
type.
var settings = Options.Create(new AppSettings { SettingOne = “ValueOne” });
var obj = new ValueController(settings);
Done! You are all set to initialize IOptions<T>
manually.
Happy Coding!