Converting IConfigurationSection to IOptions

asp.net-core asp.net-core-2.0 c# entity-framework-core

Question

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?

1
3
4/18/2020 12:26:48 AM

Accepted Answer

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);
8
2/19/2020 8:19:20 PM

Popular Answer

ServiceCollectionContainerBuilderExtensions makes this work in the SoapCore

The part from my application worked out like that:

            services.AddSingleton<IRESAdapterService>(new RESAdapterService(
                new XController(
                    services.BuildServiceProvider().GetRequiredService<IOptions<XApiSettingsFromJsonClass>>(),
                    _xLogger
                    )));

Also usable in the integrity unittests



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow