.NET Core开发实战(第13课:配置绑定:使用强类型对象承载配置数据)--学习笔记

13 | 配置绑定:使用强类型对象承载配置数据

要点:

1、支持将配置值绑定到已有对象

2、支持将配置值绑定到私有属性上

继续使用上一节代码

首先定义一个类作为接收配置的实例

class Config
{
    public string Key1 { get; set; }
    public bool Key5 { get; set; }
    public int Key6 { get;  set; }
}

接着看一下配置文件,appsettings.json

{
  "Key1": "Value1",
  "Key2": "Value2",
  "Key5": true,
  "Key6": 0
}

新增一个引用包

  • Microsoft.Extensions.Configuration.Binder

这个包的作用就是让我们能够很方便的把配置绑定到强类型上面去

主程序

var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsettings.json", optional:true, reloadOnChange:true);
var configurationRoot = builder.Build();

var config = new Config()
{
    Key1 = "config key1",
    Key5 = false,
    Key6 = 100
};

configurationRoot.Bind(config);

Console.WriteLine($"Key1:{config.Key1}");
Console.WriteLine($"Key5:{config.Key5}");
Console.WriteLine($"Key6:{config.Key6}");

启动程序,输出如下:

Key1:Value1
Key5:True
Key6:0

可以看出,绑定的字段都是从配置中读出来的

实际上通常意义来讲,配置文件不会这么简单,一般都是有嵌套格式

{
  "Key2": "Value2",
  "Key6": 0,
  "OrderService": {
    "Key1": "order key1",
    "Key5": true,
    "Key6": 200
  }
}

在这种情形下,需要把 section 绑定给 config 对象

configurationRoot.GetSection("OrderService").Bind(config);

这样就可以对不同的配置进行分组,并且分别绑定,避免配置混在一起

启动程序,输出如下:

Key1:order key1
Key5:True
Key6:200

也就是说可以从任意的节来读取配置,并且绑定到类型上面

这里定义的所有类型,所有的字段都是 public,但有一些场景下面可能是 private,对于私有的字段,默认情况下,是不会去绑定的,也不允许赋默认值,可以在定义时设置

class Config
{
    public string Key1 { get; set; }
    public bool Key5 { get; set; }
    public int Key6 { get; private set; } = 100;
}

主程序

var config = new Config()
{
    Key1 = "config key1",
    Key5 = false
};

configurationRoot.GetSection("OrderService").Bind(config);

启动程序,输出如下:

Key1:order key1
Key5:True
Key6:100

可以看到 Key6 的值是100,没有发生变化,而配置中的值是200

要让私有变量生效,实际上 Bind 还有另外一个参数

configurationRoot.GetSection("OrderService").Bind(config,
                binderOptions => { binderOptions.BindNonPublicProperties = true; });

启动程序,输出如下:

Key1:order key1
Key5:True
Key6:200

这样一来,私有字段也都可以从配置里面赋值了

知识共享许可协议

本作品采用知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议进行许可。

欢迎转载、使用、重新发布,但务必保留文章署名 郑子铭 (包含链接: http://www.cnblogs.com/MingsonZheng/ ),不得用于商业目的,基于本文修改后的作品务必以相同的许可发布。

如有任何疑问,请与我联系 (MingsonZheng@outlook.com) 。

原文地址:https://www.cnblogs.com/MingsonZheng/p/12387527.html