1. 程式人生 > 其它 >配置系統-讀取配置2

配置系統-讀取配置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<Sql>(); NoSql noSql = configurationRoot.GetSection("nosql").Get<NoSql>(); 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<Student>();
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]}列";
    }
}

再來看輸出: