.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
  }
}

在这种情形下,需要把 p 绑定给 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

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值