首页 > 解决方案 > 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始终为空;

标签: c#asp.net-mvcasp.net-core-mvcasp.net-core-2.0

解决方案


首先,Configure所做的就是

  1. 将配置部分绑定到特定类型并
  2. 将该类型注册到服务集合中,以便可以直接注入。

因此,如果Configure没有超载来做你想做的事,你可以简单地跳到个别任务,即

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

推荐阅读