
.net core 使用强类型对象承载配置数据
要点
- 支持将配置值绑定到已有对象
- 支持将配置值绑定到私有的属性上
简单示例
项目结构
附加新的包
- Microsoft.Extensions.Configuration.Binder
修改内容
appsetting.json
{
"Key1": "Value1",
"Key2": "Value2",
"Key5": false,
"Key6": 0
}
Program.cs
static void Main(string[] args)
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsetting.json",optional:false,reloadOnChange:true);
var configurationRoot = builder.Build();
var config = new Config() {
Key1="config Key1",
Key5=false,
Key6=1000
};
configurationRoot.Bind(config);
Console.WriteLine($"Key1:{config.Key1}");
Console.WriteLine($"Key5:{config.Key5}");
Console.WriteLine($"Key6:{config.Key6}");
Console.ReadKey();
}
class Config
{
public string Key1 { get; set; }
public bool Key5 { get; set; }
public int Key6 { get; set; }
}
运行结果
我们发现配置数据发生了一些改变
修改部分代码运行
修改appsetting.json配置
{
"Key1": "Value1",
"Key2": "Value2",
"Key5": false,
"Key6": 0,
"OrderService": {
"Key1": "Order key5",
"Key5": true,
"Key6": 200
}
}
Program.cs
static void Main(string[] args)
{
var builder = new ConfigurationBuilder();
builder.AddJsonFile("appsetting.json",optional:false,reloadOnChange:true);
var configurationRoot = builder.Build();
var config = new Config() {
Key1="config Key1",
Key5=false,
Key6=1000
};
configurationRoot.GetSection("OrderService").Bind(config);
Console.WriteLine($"Key1:{config.Key1}");
Console.WriteLine($"Key5:{config.Key5}");
Console.WriteLine($"Key6:{config.Key6}");
Console.ReadKey();
}
运行结果
我们发现并没有发生变化
设置属性,私有字段赋值
configurationRoot.GetSection("OrderService").Bind(config,binderOptions=> { binderOptions.BindNonPublicProperties = true; });
再次运行
欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739
评价
排名
2
文章
634
粉丝
44
评论
93
docker中Sware集群与service
尘叶心繁 : 想学呀!我教你呀
一个bug让程序员走上法庭 索赔金额达400亿日元
叼着奶瓶逛酒吧 : 所以说做程序员也要懂点法律知识
.net core 塑形资源
剑轩 : 收藏收藏
映射AutoMapper
剑轩 :
好是好,这个对效率影响大不大哇,效率高不高
一个bug让程序员走上法庭 索赔金额达400亿日元
剑轩 : 有点可怕
ASP.NET Core 服务注册生命周期
剑轩 :
http://www.tnblog.net/aojiancc2/article/details/167
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:
50010702506256


欢迎加群交流技术