前言 配置 在我們開發過程中必不可少, ASP.NET 中的配置在 中。也可配置在如:JSON、XML、資料庫等(但 ASP.NET 並沒提供相應的模塊和方法)。 在 ASP.NET Core 中 Web.config 已經不存在了(但如果托管到 IIS 的時候可以使用 web.config 配置 ...
前言
配置在我們開發過程中必不可少,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
的配置信息。- 多層級用
:
來分割,但如果是環境變數則存在跨平臺問題 查看具體細節 - 上面這種寫法是沒緩存的即:
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
的文件,都會觸發該事件
寫在最後
寫的有點亂希望不要見怪,本以為一個配置模塊應該不會複雜,但看了源代碼後發現裡面的東西好多...
本來還想寫下是如何實現的,但感覺太長了就算了。
最後還是希望大家以批判的角度來看,有任何問題可在留言區留言!