ASP.NET Core 中的配置
前言
配置在我們開發過程中必不可少,ASP.NET
中的配置在Web.config
中。也可配置在如:JSON、XML、資料庫等(但ASP.NET
並沒提供相應的模組和方法)。
在ASP.NET Core 中Web.config 已經不存在了(但如果託管到 IIS 的時候可以使用 web.config 配置 IIS),
而是用appsettings.json 和appsettings.(Development、Staging、Production).json 配置檔案
(可以理解為ASP.NET 中的Web.config 和Web.Release.config 的關係)。
下面我們一起看下ASP.NET Core 中的配置
基礎用法
HomeController.cs
:
[ApiController] public class HomeController : ControllerBase { private readonly IConfiguration _configuration; public HomeController(IConfiguration configuration) { _configuration = configuration; } [HttpGet("/")] public dynamic Index() { return JsonConvert.SerializeObject(new { ConnectionString = _configuration["ConnectionString"], Child1 = _configuration["Parent:Child1"], Grandchildren = _configuration["Parent:Child2:Grandchildren"] }); } }
返回結果:
{ "ConnectionString": "data source=.;initial catalog=TEST;user id=sa", "Child1": "child", "Grandchildren": "grandchildren" }
對應appsettings.json
的值:
{ "ConnectionString": "data source=.;initial catalog=TEST;user id=sa;password=123", "Parent": { "Child1": "child1", "Child2": "child2" } }
需要注意的:
- 鍵不區分大小寫。 例如,ConnectionString 和 connectionstring 被視為等效鍵。
-
如果鍵名相同(包含所有載入的配置檔案),以最後一個值為準。
所以
appsettings.(Development、Staging、Production).json
會覆蓋appsettings.json
的配置資訊。-
多層級用
:
來分割,但如果是環境變數則存在跨平臺問題ofollow,noindex" target="_blank">檢視具體細節 -
上面這種寫法是沒快取的即:
appsettings.json
修改後,獲取的值會立即改變
-
多層級用
繫結到物件 IOptions<TestOptions>
對於_configuration["Parent:Child2:Grandchildren"]
的寫法對程式員來說肯定很反感,下面我們看下把配置檔案繫結到物件中。
-
首先把 JSON 物件轉換成物件
public class TestOptions { public string ConnectionString { get; set; } public Parent Parent { get; set; } } public class Parent { public string Child1 { get; set; } public Child2 Child2 { get; set; } } public class Child2 { public string GrandChildren { get; set; } }
-
在
Startup.cs
的ConfigureServices
方法新增程式碼:services.Configure<TestOptions>(Configuration);
-
HomeController.cs
:[ApiController] public class HomeController : ControllerBase { private readonly IOptions<TestOptions> _options; public HomeController(IOptions<TestOptions> options) { _options = options; } [HttpGet("options")] public string Options() { return JsonConvert.SerializeObject(_options); } }
返回的結果如下:
{ "Value": { "ConnectionString": "data source=.;initial catalog=TEST;user id=sa", "Parent": { "Child1": "child", "Child2": { "GrandChildren": "grandchildren" } } } }
發現
-
如果我們修改
appsettings.json
,然後重新整理頁面,會發現值並沒用變 -
我們發現根節點是
Value
根據上面 2 個問題我們去看原始碼:
首先找到這句:
services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptions<>), typeof(OptionsManager<>)));
我們去看
OptionsManager
方法:public class OptionsManager<TOptions> : IOptions<TOptions>, IOptionsSnapshot<TOptions> where TOptions : class, new() { private readonly IOptionsFactory<TOptions> _factory; // 註解: _cache 為 ConcurrentDictionary<string, Lazy<TOptions>>() // 不知道注意到上面注入方法沒,用的是 Singleton 單例,所以更新配置檔案後沒及時更新 private readonly OptionsCache<TOptions> _cache = new OptionsCache<TOptions>(); public OptionsManager(IOptionsFactory<TOptions> factory) { _factory = factory; } /// <summary> /// TOptions的預設配置例項 /// 這裡就是為什麼根節點為Value /// </summary> public TOptions Value { get { return Get(Options.DefaultName); } } /// <summary> /// 該方法在 IOptionsSnapshot 介面中 /// </summary> public virtual TOptions Get(string name) { name = name ?? Options.DefaultName; // Store the options in our instance cache return _cache.GetOrAdd(name, () => _factory.Create(name)); } }
繫結到物件 IOptionsSnapshot<TestOptions>
-
與
IOptions<TestOptions>
的用法一樣,區別就是依賴注入的生命週期為Scoped ,所以沒快取,直接看程式碼:services.TryAdd(ServiceDescriptor.Scoped(typeof(IOptionsSnapshot<>), typeof(OptionsManager<>)));
-
IOptionsSnapshot<TOptions> 比IOptions<TOptions> 多了個方法
TOptions Get(string name);
Value
屬性其實就是呼叫了該方法,只是name
為Options.DefaultName
-
IOptionsSnapshot<TOptions> 繼承了IOptions<TOptions> (這裡有個疑問,上面的
OptionsManager<TOptions>
繼承了IOptions<TOptions>, IOptionsSnapshot<TOptions>
2 個介面,也許是為了清晰吧)。
自定義配置檔案(JSON)
有的時候配置資訊很多,想在單獨的檔案中配置,ASP.NET Core 提供了INI 、XML 、JSON 檔案系統載入配置的方法。
-
首先在Program.cs 的
CreateWebHostBuilder
方法中新增如下程式碼:public static IWebHostBuilder CreateWebHostBuilder(string[] args) { return WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { //設定根目錄,我們放在 /Config 資料夾下 // 此種寫法不會載入`appsettings.json` // config.SetBasePath(Path.Combine(Directory.GetCurrentDirectory(), "Config")); config.SetBasePath(Directory.GetCurrentDirectory()); //新增 setting.json 配置檔案 //optional: 檔案是否可選,當為false時 如果檔案不存在 程式啟動不起來 //reloadOnChange:檔案改變後是否重新載入 config.AddJsonFile("Config/setting.json", optional: false, reloadOnChange: false); }) .UseStartup<Startup>(); }
我們看下reloadOnChange 引數處理了哪些事情:
if (Source.ReloadOnChange && Source.FileProvider != null) { ChangeToken.OnChange( //監視檔案 如果改變就執行 Load(true) 方法 () => Source.FileProvider.Watch(Source.Path), () => { Thread.Sleep(Source.ReloadDelay); Load(reload: true); }); }
-
建立setting.json :
{ "Rookie": { "Name": "DDD", "Age": 12, "Sex": "男" } }
-
在 Controller 中:
[Route("api/[controller]")] [ApiController] public class OptionsController : ControllerBase { private readonly IConfiguration _configuration; public OptionsController(IConfiguration configuration) { _configuration = configuration; } [HttpGet] public string Index() { return JsonConvert.SerializeObject(new { Name = _configuration["Rookie:Name"], Age = _configuration["Rookie:Age"], Sex = _configuration["Rookie:Sex"] }); } }
自定義配置檔案(JSON)繫結到物件
通過上面配置發現獲取配置用的是_configuration["Name"]
方式,下面我們繫結到物件上
-
定義配置物件Setting 類
-
在Startup.cs 的
ConfigureServices
方法新增程式碼:services.Configure<Setting>(Configuration.GetSection("Rookie"));
GetSection
方法:獲得指定鍵的配置子部分 -
用法和上面一樣
不知道發現個情況沒,我們setting.json 的配置檔案的資訊也是存到_configuration 中的,如果檔案多了很可能會覆蓋節點,下面我們換一種寫法。
-
首先刪除Program.cs 中
CreateWebHostBuilder
方法的程式碼:config.AddJsonFile("Config/setting.json", optional: false, reloadOnChange: true); -
修改配置檔案setting.json :
{ "Name": "DDD", "Age": 12, "Sex": "男" }
-
在中Startup.cs 的
ConfigureServices
方法中新增:var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("Config/setting.json", optional: false, reloadOnChange: true) .Build(); services.Configure<Setting>(config);
這樣就不會影響 全域性 的配置資訊了
其他方式
-
我們看下下面 2 個方式:
[Route("[controller]")] [ApiController] public class HomeController : ControllerBase { private readonly IConfiguration _configuration; private readonly TestOptions _bindOptions = new TestOptions(); private readonly Parent _parent = new Parent(); public HomeController(IConfiguration configuration) { //全部繫結 _configuration.Bind(_bindOptions); //部分繫結 _configuration.GetSection("Parent").Bind(_parent); } [HttpGet("options")] public string Options() { return JsonConvert.SerializeObject(new { BindOptions = _bindOptions, Parent = _parent }); } }
個人感覺這種方式有點多餘 ( ╯□╰ )
-
IOptionsMonitor 、IOptionsFactory 、IOptionsMonitorCache 方式:
我們看如下程式碼
services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptions<>), typeof(OptionsManager<>))); services.TryAdd(ServiceDescriptor.Scoped(typeof(IOptionsSnapshot<>), typeof(OptionsManager<>))); services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptionsMonitor<>), typeof(OptionsMonitor<>))); services.TryAdd(ServiceDescriptor.Transient(typeof(IOptionsFactory<>), typeof(OptionsFactory<>))); services.TryAdd(ServiceDescriptor.Singleton(typeof(IOptionsMonitorCache<>), typeof(OptionsCache<>)));
這裡只說下
IOptionsMonitor<>
:[Route("[controller]")] [ApiController] public class HomeController : ControllerBase { private readonly IOptionsMonitor<TestOptions> _optionsMonitor; public HomeController(IOptionsMonitor<TestOptions> optionsMonitor , ILogger<HomeController> logger) { _optionsMonitor = optionsMonitor; _logger = logger; } [HttpGet("options")] public string Options() { //這裡有個變更委託 _optionsMonitor.OnChange((options, name) => { var info = JsonConvert.SerializeObject(new { Options = options, Name = name }); _logger.LogInformation($"配置資訊已更改:{info}"); }); return JsonConvert.SerializeObject(new { OptionsMoitor = _optionsMonitor }); }
當我們修改配置檔案後會看到日誌資訊:
info: WebApiSample.Controllers.HomeController[0]
配置資訊已更改:{"Options":{"ConnectionString":"data source=.;initial catalog=TEST;user id=sa","Parent":{"Child1":"child","Child2":{"GrandChildren":"grandchildren"}}},"Name":"TestOptions"}
info: WebApiSample.Controllers.HomeController[0]
配置資訊已更改:{"Options":{"ConnectionString":"data source=.;initial catalog=TEST;user id=sa","Parent":{"Child1":"child","Child2":{"GrandChildren":"grandchildren"}}},"Name":"TestOptions"}
info: WebApiSample.Controllers.HomeController[0]
配置資訊已更改:{"Options":{"ConnectionString":"data source=.;initial catalog=TEST;user id=sa","Parent":{"Child1":"child","Child2":{"GrandChildren":"grandchildren"}}},"Name":"TestOptions"}
info: WebApiSample.Controllers.HomeController[0]
配置資訊已更改:{"Options":{"ConnectionString":"data source=.;initial catalog=TEST;user id=sa","Parent":{"Child1":"child","Child2":{"GrandChildren":"grandchildren"}}},"Name":"TestOptions"}
不知道為什麼會有這麼多日誌...
還有一點不管我們修改哪個日誌檔案,只要是執行了
AddJsonFile
的檔案,都會觸發該事件
寫在最後
寫的有點亂希望不要見怪,本以為一個配置模組應該不會複雜,但看了原始碼後發現裡面的東西好多... 本來還想寫下是如何實現的,但感覺太長了就算了。 最後還是希望大家以批判的角度來看,有任何問題可在留言區留言!