Converting IConfigurationSection to IOptions

我怕爱的太早我们不能终老 提交于 2019-12-11 03:56:51

问题


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?view=aspnetcore-2.1

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:


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 is an IOptions<T>, you can use Options.Create, like this:

IOptions<MyCustomOptions> myOptions = Options.Create(myCustomOptions);



回答2:


I guess you need Bind method:

var config = new ConfigurationBuilder()...Build();
var myOptions = new MyOptions();
config.GetSection("MyOptions").Bind(myOptions);



回答3:


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



来源:https://stackoverflow.com/questions/53166201/converting-iconfigurationsection-to-ioptions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!