上節演示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沒有變化!

轉載請註明出處,本文鏈接:https://www.uj5u.com/net/227008.html
標籤:.NET技术
上一篇:在 ASP.NET Core 中將依賴項注入到控制器
下一篇:UDP 協議 C# UdpClient亂序接收資料包丟失的問題 Socket ReceiveBufferSize
