1. 程式人生 > 實用技巧 >.Net Core 3.x Api開發筆記 -- 讀取配置檔案資訊(四)

.Net Core 3.x Api開發筆記 -- 讀取配置檔案資訊(四)

上節演示Autofac使用,連線:.Net Core 3.x Api開發筆記 -- IOC,使用Autofac實現依賴注入(三)

本節演示如何讀取應用配置資訊,也就是讀取appsettings.json 檔案中的配置資訊

本節通過讀取資料庫配置檔案做完演示:

第1步:在 appsettings.json 新增資料庫配置檔案

1   //資料庫連線字串
2   "DBConfig": {
3     "DBType": "Mysql", //mysql、mssql、oracle
4     "DBConnectionString": "Data Source=localhost;Database=MyShop;User Id=root;Password=123456;CharSet=utf8;port=3306
", //mysql連線字串 5 "DBTimeout": 180, //180s 單位秒 6 "RedisConnectionString": "127.0.0.1:6379,password=123456,abortConnect=false" //redis連線字串 7 }

第2步:新建一個類:DBConfig,用於存放上述配置檔案內容

    public class DBConfig
    {
        /// <summary>
        /// 資料庫型別  mysql、mssql、oracle
        /// </summary>
        public
string DBType { get; set; } /// <summary> /// 連結字串 /// </summary> public string DBConnectionString { get; set; } /// <summary> /// 連結超時時間 /// </summary> public string DBTimeout { get; set; } /// <summary> /// redis連結字串
/// </summary> public string RedisConnectionString { get; set; } } //全域性配置 public class SystemContext { /// <summary> /// 讀取資料庫配置檔案 /// </summary> public static DBConfig dbConfig { get; set; } }

第三步:在 Startup 檔案中初始化配置檔案內容

 1         public void ConfigureServices(IServiceCollection services)
 2         {
 3             services.AddControllers();
 4 
 5             //方式1
 6             //讀取配置檔案appsettings.json,將自定義節點繫結到DBConfig類中,在任意地方直接使用
 7             //配置檔案更新,繫結的值不會實時更新
 8             SystemContext.dbConfig = Configuration.GetSection("DBConfig").Get<DBConfig>();
 9 
10             //方式2 
11             //將DBConfig物件註冊到Service中,這樣可以在Controller中注入使用
12             //配置檔案更新,繫結的值會實時更新
13             services.Configure<DBConfig>(Configuration.GetSection("DBConfig"));
14         }

上邊有兩種配置方式,可以任選一種,方式1不會實時更新配置檔案內容,方式2會實時更新配置檔案內容,根據業務需求自由選擇

第四步:在應用中使用

 1         private readonly IOptionsSnapshot<DBConfig> dbConfig;   //通過注入方式讀取配置檔案
 2 
 3         public UserController(IOptionsSnapshot<DBConfig> _dbConfig)
 4         {
 5             dbConfig = _dbConfig;
 6         }
 7 
 8         [HttpGet]
 9         public async Task<IActionResult> GetConfig()
10         {
11             var result = await Task.Run(() =>
12             {
13                 //方式1 讀取配置檔案  不會實施更新內容
14                 var dbType = SystemContext.dbConfig.DBType.ToLower();
15                 return dbType;
16             });
17 
18             //方式2 讀取配置檔案  可以實施更新內容
19             var result2 = dbConfig.Value.DBType.ToLower();
20 
21             return Ok("方式1:" + result + ",方式2:" + result2);
22         }

最後測試結果顯示,方式2 會跟隨配置檔案內容的變更實時更新,而方式1沒有變化!