Skip to main content

How to Create IOptions Instance

It’s pretty standard for classes to require configuration in their constructors in the IOptions form.
But, this doesn’t make testing very easy.

Here’s a workaround for pushing an IOptions instance into a class constructor, that needs config.

This example is for a class, ValueController, which has a constructor that requires an instnace of: IOptions<AppSettings>

var settings = Options.Create(new AppSettings { SettingOne = "ValueOne" });
var obj = new ValueController(settings);

The first like creates a new instance of AppSettings (you can inject your own if it already exists), and wraps it into an IOptions class. This latter class instance is passed on to the constructor as if the config came from DI.

This method was taken from here: Looking for a way to initialize IOptions<T> manually?