13:配置绑定:使用强类型对象承载配置数据-.NET Core开发实战
.NET Core开发实战前文传送门:
- 第1课:课程介绍
- 第2课:内容综述
- 第3课:.NET Core的现状、未来以及环境搭建
- 第4课:Startup:掌握ASP.NET Core的启动过程
- 第5课:依赖注入:良好架构的起点(上)
- 第5课:依赖注入:良好架构的起点(中)
- 第5课:依赖注入:良好架构的起点(下)
- 第6课:作用域与对象释放行为(上)
- 第6课:作用域与对象释放行为(下)
- 第7课:用Autofac增强容器能力(上)
- 第7课:用Autofac增强容器能力(下)
- 第8课:配置框架:让服务无缝适应各种环境
- 第9课:命令行配置提供程序
- 第10课:环境变量配置提供程序
- 第11课:文件配置提供程序
- 第12课:配置变更监听
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
这样一来,私有字段也都可以从配置里面赋值了

原文出处:微信公众号【DotNet NB】,作者【郑子铭】
原文链接:https://mp.weixin.qq.com/s/emFbM3AQX93uZmVV9hPS6A
本文观点不代表Dotnet9立场,转载请联系原作者。