gpt4 book ai didi

c# - Mvc Core动态绑定(bind)配置

转载 作者:太空宇宙 更新时间:2023-11-03 18:53:35 25 4
gpt4 key购买 nike

我想知道是否可以将配置部分动态绑定(bind)到对象。通常要绑定(bind)配置部分,我们会编写如下代码:

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

例如,如果我想绑定(bind)注入(inject),我可以这样做:

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 所做的就是

  1. 将配置部分绑定(bind)到一个特定的类型和
  2. 在服务集合中注册该类型,以便可以直接注入(inject)。

因此,如果 Configure 没有重载来执行您想要的操作,您可以简单地跳转到各个任务,即

services.AddSingleton(p =>
{
var config = Activator.CreateInstance(type);
Configuration.GetSection("Foo").Bind(config);
return config;
}

关于c# - Mvc Core动态绑定(bind)配置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51027443/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com