配置系统-读取配置2
将配置映射成对象:
基础:Step1.新建项目:
-- Config.Json
{ "sql": { "oracle": "oracleoracleoracleoracleoracleoracle", "mysql": "mysqlmysqlmysqlmysqlmysqlmysqlmysqlmysql", "db2": "db2db2db2db2db2db2db2db2db2db2db2db2db2db2", "mssql": "mssqlmssqlmssqlmssqlmssqlmssqlmssqlmssql", "npgsql": "npgsqlnpgsqlnpgsqlnpgsqlnpgsqlnpgsql" }, "nosql": { "mongodb": "mongodbmongodbmongodb", "redis": "redisredisredisredisredis" } }
-- Program.cs
添加NUGET:
Install-Package Microsoft.Extensions.Configuration
Install-Package Microsoft.Extensions.Configuration.Json
Install-Package Microsoft.Extensions.Configuration.Binder
using Microsoft.Extensions.Configuration; ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.AddJsonFile("Config.json", true/*防止读取出错*/, true/*文件变更重新加载*/);//加载文件 IConfigurationRoot configurationRoot = configurationBuilder.Build(); Sql sql= configurationRoot.GetSection("sql").Get(); NoSql noSql = configurationRoot.GetSection("nosql").Get (); Console.WriteLine("sql:"+sql.db2); Console.WriteLine("NoSql:" + noSql.Mongodb); class Sql { public string MySql { get; set; } public string Oracle { get; set; } public string mssql { get; set; } public string db2 { get; set; } public string npgsql { get; set; } } class NoSql { public string Mongodb { get; set; } public string Redis { get; set; } }
查看输出结果
-----------------------------------------------------------------------------------------------------------------------------------------------------------
进阶:修改配置文件
{ "name": "zhangsan", "age": 18, "classInfo": { "teacher": "Miss Wang", "className": "grade one", "seat": [2,8] } }
-- Program.cs
using Microsoft.Extensions.Configuration; ConfigurationBuilder configurationBuilder = new ConfigurationBuilder(); configurationBuilder.AddJsonFile("Config.json", true/*防止读取出错*/, true/*文件变更重新加载*/);//加载文件 IConfigurationRoot configurationRoot = configurationBuilder.Build(); Student stu = configurationRoot.Get(); Console.WriteLine(stu.ToString()); Console.WriteLine(stu.classInfo.ToString()); class Student { public string Name { get; set; } public int Age { get; set; } public ClassInfo classInfo { get; set; } public override string ToString() { return $"我是{Name},今年{Age}岁"; } } class ClassInfo { public string Teacher { get; set; } public string ClassName { get; set; } public int[] Seat { get; set; } public override string ToString() { return $"老师是{Teacher} 班级:{ClassName} 坐在第{Seat[0]}排第{Seat[1]}列"; } }
再来看输出: