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 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 dependency (take an example of Unit test cases) and then 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 to 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!
Top comments (2)
Hi, there are also a bunch of other methods to map a section in the
appsettings.json
to a configuration object. See: Options patternThis is my favorite method to do it:
(Services is the
IServiceCollection
and Configuration is theIConfiguration
).Yes, there are a bunch of ways to register configuration classes using DI but in this article, I am initializing
IOptions<T>
without dependency injection. e.g. In the Unit test cases project we don't have DI to injectIOptions
so might be helpful there.Thanks for the input David!