第13课:配置绑定:使用强类型对象承载配置数据
学习分享 丨作者 / 郑 子 铭 丨公众号 / DotNet NB / CloudNative NB
要点:
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这样一来,私有字段也都可以从配置里面赋值了
GitHub源码链接:https://github.com/MingsonZheng/DotNetCoreDevelopmentActualCombat/tree/main/ConfigurationFileDemo
Last updated