tnblog
首页
视频
资源
登录

.net core 使用强类型对象承载配置数据

6045人阅读 2020/6/28 15:45 总访问:3660906 评论:0 收藏:0 手机
分类: .net后台框架

.netcore

.net core 使用强类型对象承载配置数据


要点


  • 支持将配置值绑定到已有对象
  • 支持将配置值绑定到私有的属性上

简单示例


项目结构


内容请参考:https://www.tnblog.net/hb/article/details/4140


附加新的包

  • Microsoft.Extensions.Configuration.Binder


修改内容


appsetting.json
  1. {
  2. "Key1": "Value1",
  3. "Key2": "Value2",
  4. "Key5": false,
  5. "Key6": 0
  6. }
Program.cs
  1. static void Main(string[] args)
  2. {
  3. var builder = new ConfigurationBuilder();
  4. builder.AddJsonFile("appsetting.json",optional:false,reloadOnChange:true);
  5. var configurationRoot = builder.Build();
  6. var config = new Config() {
  7. Key1="config Key1",
  8. Key5=false,
  9. Key6=1000
  10. };
  11. configurationRoot.Bind(config);
  12. Console.WriteLine($"Key1:{config.Key1}");
  13. Console.WriteLine($"Key5:{config.Key5}");
  14. Console.WriteLine($"Key6:{config.Key6}");
  15. Console.ReadKey();
  16. }
  17. class Config
  18. {
  19. public string Key1 { get; set; }
  20. public bool Key5 { get; set; }
  21. public int Key6 { get; set; }
  22. }

运行结果

运行结果

我们发现配置数据发生了一些改变


修改部分代码运行


修改appsetting.json配置

  1. {
  2. "Key1": "Value1",
  3. "Key2": "Value2",
  4. "Key5": false,
  5. "Key6": 0,
  6. "OrderService": {
  7. "Key1": "Order key5",
  8. "Key5": true,
  9. "Key6": 200
  10. }
  11. }
Program.cs
  1. static void Main(string[] args)
  2. {
  3. var builder = new ConfigurationBuilder();
  4. builder.AddJsonFile("appsetting.json",optional:false,reloadOnChange:true);
  5. var configurationRoot = builder.Build();
  6. var config = new Config() {
  7. Key1="config Key1",
  8. Key5=false,
  9. Key6=1000
  10. };
  11. configurationRoot.GetSection("OrderService").Bind(config);
  12. Console.WriteLine($"Key1:{config.Key1}");
  13. Console.WriteLine($"Key5:{config.Key5}");
  14. Console.WriteLine($"Key6:{config.Key6}");
  15. Console.ReadKey();
  16. }

运行结果

运行结果

我们发现并没有发生变化


设置属性,私有字段赋值

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

再次运行

再次运行


欢迎加群讨论技术,1群:677373950(满了,可以加,但通过不了),2群:656732739

评价
这一世以无限游戏为使命!
排名
2
文章
657
粉丝
44
评论
93
docker中Sware集群与service
尘叶心繁 : 想学呀!我教你呀
一个bug让程序员走上法庭 索赔金额达400亿日元
叼着奶瓶逛酒吧 : 所以说做程序员也要懂点法律知识
.net core 塑形资源
剑轩 : 收藏收藏
映射AutoMapper
剑轩 : 好是好,这个对效率影响大不大哇,效率高不高
ASP.NET Core 服务注册生命周期
剑轩 : http://www.tnblog.net/aojiancc2/article/details/167
ICP备案 :渝ICP备18016597号-1
网站信息:2018-2025TNBLOG.NET
技术交流:群号656732739
联系我们:contact@tnblog.net
公网安备:50010702506256
欢迎加群交流技术