c# - Mvc Core 动态绑定配置
问题描述
我想知道是否可以将配置部分动态绑定到对象。通常要绑定配置部分,我们会编写如下代码:
var section = Configuration.GetSection(nameof(MyCustomSection));
services.Configure<MyCustomSection>(o => secto.Bind(o));
我想知道是否可以在不声明类型的情况下做到这一点<MyCustomSection>
。
//This doesn't work, just trying to show you how I would like to do it
services.Configure(MyType, o => section.Bind(o));
例如,如果我想绑定注入,我可以这样做:
services.AddTransient<IDateTime, SystemDateTime>();
但我也可以像这样动态地做到这一点:
services.AddTransient(Type1, Type2));
同样可能services.Configure
吗?我查看了方法参数,但似乎不支持它。只是想知道是否有另一种方法,或者我只是忽略了一些东西?
编辑:
services.AddSingleton(p =>
{
var type = new MySection();
Configuration.GetSection("MySection").Bind(type);
return type;
});
然后我在这样的类中调用它:
public class Test {
public Test(IOptions<MySection> section)
{
var finalValue = section.Value;
}
}
finalValue
始终为空;
解决方案
首先,Configure
所做的就是
- 将配置部分绑定到特定类型并
- 将该类型注册到服务集合中,以便可以直接注入。
因此,如果Configure
没有超载来做你想做的事,你可以简单地跳到个别任务,即
services.AddSingleton(p =>
{
var config = Activator.CreateInstance(type);
Configuration.GetSection("Foo").Bind(config);
return config;
}
推荐阅读
- asp.net-mvc - 将数据从文件 .cs 或 cshtml 文件的值发送到 js MVC
- windows - 如何在 Windows 上抑制控制台窗口?
- jpa - 通过将 ID 传递给 IN 子句的 JPQL 订单实体
- python - 当参数包含特殊字符或空格时,/profile/preview/ 处的 NoReverseMatch
- android - 带有 MutableContextWrapper VS 片段的自定义视图
- sql - 如何从字符串日期c#中获取年份
- c - 将文本文件读入C中的数组
- java - AndroidStudio 无法运行单个参数化测试
- intel - 英特尔内置显卡 (Intel Iris Plus Graphics 655) 上的 OpenACC
- xero-api - Xero API中发票的Oauth2范围?