将IConfigurationSection转换为IOptions [英] Converting IConfigurationSection to IOptions

查看:336
本文介绍了将IConfigurationSection转换为IOptions的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

选项"模式使我可以创建包含配置值的选项对象,如下所述: https://docs.microsoft.com/zh-cn/aspnet/core/fundamentals/configuration/options

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

我需要IDesignTimeDbContextFactory实现中一个选项对象的值,以供EF在创建模型时使用. (该配置部分中的值将用于数据播种,因此我向数据库上下文构造函数中添加了IOptions.)

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.)

由于我无权访问IServiceCollection(因为它是设计时间,就像运行"dotnet ef migrations add"时一样),所以我需要有另一种方法可以将IConfigurationSection(代表我感兴趣的部分)转换为我的自定义选项课.

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?

推荐答案

您可以使用

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.

要将其包装在IOptions<T>中,请使用

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

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

这篇关于将IConfigurationSection转换为IOptions的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆