如何在.net Core应用程序中使用IConfiguration绑定多级配置对象? [英] How do I bind a multi level configuration object using IConfiguration in a .net Core application?

查看:1046
本文介绍了如何在.net Core应用程序中使用IConfiguration绑定多级配置对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试绑定到应该由appsettings.json文件填充的自定义配置对象。

I'm trying to bind to a custom configuration object which should be populated by an appsettings.json file.

我的appsettings有点像:

My appsettings looks a bit like:

{
  "Logging": {
    "IncludeScopes": true,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  "Settings": {
    "Foo": {
      "Interval": 30,
      "Count": 10
    }
  }
}

设置类如下:

public class Settings
{
  public Foo myFoo {get;set;}
}

public class Foo
{
  public int Interval {get;set;}
  public int Count {get;set;}

  public Foo()
  {}

  // This is used for unit testing. Should be irrelevant to this question, but included here for completeness' sake.
  public Foo(int interval, int count)
  {
    this.Interval = interval;
    this.Count = count;
  }
}

当我尝试将配置绑定到对象时,最低工作水平:

When I try to bind the Configuration to an object the lowest level it works:

Foo myFoo = Configuration.GetSection("Settings:Foo").Get<Foo>();

myFoo 正确地具有时间间隔计数,其值分别设置为30和10。

myFoo correctly has an Interval and a Count with values set to 30 and 10 respectively.

但这不是:

Settings mySettings = Configuration.GetSection("Settings").Get<Settings>();

mySettings 为空 foo

令人沮丧的是,如果我使用调试器,可以看到正在读取必需的数据 来自appsettings.json文件。我可以进入 Configuration =>非公众成员=> _providers => [0] =>数据,然后查看我需要的所有信息。

Frustratingly, if I use the debugger I can see that the necessary data is being read in from the appsettings.json file. I can step down into Configuration => Non-Public Members => _providers => [0] => Data and see all of the information I need. It just won't bind for a complex object.

推荐答案

您的属性必须与 appsettings.json中的属性名称匹配。

Your property must match the property names in "appsettings.json".

您必须将设置的 myFoo 属性重命名为 Foo ,因为这是json文件中的属性名称。

You must rename your Settings' myFoo property into Foo, because that's property name in the json file.

这篇关于如何在.net Core应用程序中使用IConfiguration绑定多级配置对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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