Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting IConfigurationSection to IOptions

The Options pattern allowed me to create options objects containing values from configuration, as described here: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/options

I need the values for one option object within an IDesignTimeDbContextFactory implementation, to be used by EF when creating the models. (The values in that config section will be used for data seeding, and so I added IOptions to the DB Context constructor.)

As I have no access to IServiceCollection (since it's design time - like when running "dotnet ef migrations add", I need to have another way to convert an IConfigurationSection (representing the section I'm interested in) to my custom Options class.

May I know how I can do this without dependency injection?

like image 611
Jonas Arcangel Avatar asked Nov 06 '18 05:11

Jonas Arcangel


People also ask

What is IOptions?

IOptionsMonitor is a Singleton service that retrieves current option values at any time, which is especially useful in singleton dependencies. IOptionsSnapshot is a Scoped service and provides a snapshot of the options at the time the IOptionsSnapshot<T> object is constructed.


2 Answers

You can use the Bind(Configuration, object) extension method to perform manual binding of any object. Here's an example:

var myCustomOptions = new MyCustomOptions();
myConfigurationSection.Bind(myCustomOptions);

// Use myCustomOptions directly.

To wrap this in an IOptions<T>, use Options.Create:

IOptions<MyCustomOptions> myOptions = Options.Create(myCustomOptions);
like image 187
Kirk Larkin Avatar answered Oct 04 '22 20:10

Kirk Larkin


you can also use

config.Get<MyCustomOptions>()

This is an extension method from Microsoft.Extensions.Configuration namespace. I see it in Assembly Microsoft.Extensions.Configuration.Binder, Version=3.1.9.0. Perhaps, it exists in earlier versions also. That would give you the Settings object itself. then you can wrap it into IOptions as Krik showed in another answer.

like image 30
Greg Z. Avatar answered Oct 04 '22 22:10

Greg Z.