Mvc Core动态绑定配置

时间:2018-06-25 15:51:37

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

我想知道是否可以将配置节动态绑定到对象。通常,为了绑定配置节,我们将编写如下代码:

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始终为空;

2 个答案:

答案 0 :(得分:3)

首先,Configure要做的就是

  1. 将配置节绑定到特定类型,然后
  2. 在服务集合中注册该类型,以便可以直接注入它。

因此,如果Configure没有执行任务所需的重载,则可以简单地跳到各个任务,即

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

答案 1 :(得分:3)

如果确实需要,可以在运行时使用反射使用动态泛型类型参数来调用[2018-06-25 16:55:21,466: INFO/MainProcess] Received task: tasks.simple_chord[c78eb259-e1e1-4b4d-b053-247afce4d536] [2018-06-25 16:55:21,660: INFO/MainProcess] Received task: tasks.first_task[fca138d2-c672-4299-a2ed-1bb5cacb66da] [2018-06-25 16:55:21,685: INFO/ForkPoolWorker-1] Task tasks.simple_chord[c78eb259-e1e1-4b4d-b053-247afce4d536] succeeded in 0.19740361299773213s: <AsyncResult: c4db6bbf-d150-44db-a34e-99ea6bd71012> [2018-06-25 16:55:21,688: INFO/MainProcess] Received task: tasks.second_body[afc32047-3239-4118-bb2c-c116f9a241bf] [2018-06-25 16:55:23,340: INFO/ForkPoolWorker-1] Task tasks.first_task[fca138d2-c672-4299-a2ed-1bb5cacb66da] succeeded in 1.639255696994951s: 'first_task' [2018-06-25 16:55:23,344: INFO/MainProcess] Received task: tasks.first_body[c4db6bbf-d150-44db-a34e-99ea6bd71012] [2018-06-25 16:55:24,099: INFO/ForkPoolWorker-1] Task tasks.second_body[afc32047-3239-4118-bb2c-c116f9a241bf] succeeded in 0.7374479610007256s: 'second_body' [2018-06-25 16:55:24,103: INFO/MainProcess] Received task: tasks.third_body[9a90c2da-cd03-4f55-9675-9194acd7d42f] [2018-06-25 16:55:24,656: INFO/ForkPoolWorker-1] Task tasks.first_body[c4db6bbf-d150-44db-a34e-99ea6bd71012] succeeded in 0.5298690330091631s: 'first_body' [2018-06-25 16:55:25,247: INFO/ForkPoolWorker-1] Task tasks.third_body[9a90c2da-cd03-4f55-9675-9194acd7d42f] succeeded in 0.5770523219980532s: 'third_body' 。但是,通过修改克里斯的答案,可能会有更简单的方法(使用services.Configure<TOptions>())来获得所需的结果。

像这样使用它:

IOptions<>


services.Configure(MyType, o => { var castObj = (MyType)o; section.Bind(castObj); });