Looking for a way to initialize IOptions<T> manually?

maheshmore2691

Mahesh More

Posted on February 22, 2022

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 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)
   {
   }
}
Enter fullscreen mode Exit fullscreen mode

Also, we have some app configuration in appsettings.json file.

{
   "AppSettings": {
       "SettingOne": "ValueOne"
   }
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

Done! You are all set to initialize IOptions<T> manually.

Happy Coding!

💖 💪 🙅 🚩
maheshmore2691
Mahesh More

Posted on February 22, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related