tnblog
首页
视频
资源
登录

.net core 简单配置框架运用

5796人阅读 2020/6/18 14:59 总访问:3467244 评论:0 收藏:0 手机
分类: .net后台框架

.netcore

Configuration 配置框架:让服务无缝适应各种环境


核心组件包


  • Microsoft.Extensions.Configuration.Abstractions
  • Microsoft.Extensions.Configuration


    配置框架


  • 以 key-value 字符串键值对的方式抽象了配置
  • 支持从各种不同的数据源读取配置(比如:命令行读取,从环境变量读取,从文件读取)


配置框架核心类型


  • IConfiguration
  • IConfigurationRoot (表示配置的根系|完成读取配置的操作实例)
  • IConfigurationSection (当我们不仅仅是通过key-value获取配置的时候使用,通过冒号(:)做分割)
  • IConfigurationBuilder (构建我们配置的核心)


配置框架扩展点


  • IConfigurationSource
  • IConfigurationProvider


简单运用


项目结构

项目结构

通过键值对获取


示例代码

  1. IConfigurationBuilder builder = new ConfigurationBuilder();
  2. builder.AddInMemoryCollection(new Dictionary<string, string>() {
  3. { "key1","value1" },
  4. { "key2","value2" },
  5. { "section1:key4","value3" }
  6. });
  7. IConfigurationRoot configurationRoot = builder.Build();
  8. //IConfiguration config = configurationRoot;
  9. Console.WriteLine(configurationRoot["key1"]);
  10. Console.WriteLine(configurationRoot["key2"]);

结果

结果

通过 IConfigurationSection 获取分组数据


添加代码

  1. IConfigurationSection section = configurationRoot.GetSection("section1");
  2. Console.WriteLine($"key4:{section["key4"]}");
  3. Console.WriteLine($"key5:{section["key5"]}");

结果

结果

通过 IConfigurationSection 获取多重分组数据


修改代码

  1. IConfigurationBuilder builder = new ConfigurationBuilder();
  2. builder.AddInMemoryCollection(new Dictionary<string, string>() {
  3. { "key1","value1" },
  4. { "key2","value2" },
  5. { "section1:key4","value3" },
  6. { "section2:key5","value5" },
  7. { "section2:key6","value6" },
  8. { "section2:section3:key7","value7" },
  9. });
  10. IConfigurationRoot configurationRoot = builder.Build();
  11. //IConfiguration config = configurationRoot;
  12. Console.WriteLine(configurationRoot["key1"]);
  13. Console.WriteLine(configurationRoot["key2"]);
  14. IConfigurationSection section = configurationRoot.GetSection("section1");
  15. Console.WriteLine($"key4:{section["key4"]}");
  16. Console.WriteLine($"key5:{section["key5"]}");
  17. IConfigurationSection section2 = configurationRoot.GetSection("section2");
  18. Console.WriteLine($"key6:{section2["key6"]}");
  19. var section3 = section2.GetSection("section3");
  20. Console.WriteLine($"key7:{section3["key7"]}");

运行结果

运行结果


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

评价

剑轩

2021/8/20 12:46:59

这......么.....长

尘叶心繁:@剑轩还有下集

2021/8/20 13:33:12 回复

这一世以无限游戏为使命!
排名
2
文章
634
粉丝
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
欢迎加群交流技术