分享主軸
IOptions<>
特點
IOptionsSnapshot<>
特點
IOptionsMonitor<>
特點
IOptions<> 和 IOptionsMonitor<> 都是單例模式,但 IOptionsMonitor<> 提供了動態更新的能力,使其能夠在設定檔案變更時自動更新設定值,而 IOptions<> 沒有辦法即時更新
有兩種,一種是強型別方式取值,一種是直接取值方式
這裡強型別方式搭配 IOptions<> 舉例,取值寫法有很多種,這邊以其中一種常見寫法,設定值資料結構可以多層,也可以單層
program.cs註冊 :
builder.Services.Configure<AppsettingsOptions>(builder.Configuration.GetSection(AppsettingsOptions.AppSettings))
appsettings.json :
{
"AppSettings": {
"AppName": "MyApplication",
"Version": "1.0.0"
}
}
創一個類別 :
public class AppsettingsOptions {
public const string AppSettings = "AppSettings";
public string AppName { get; set; }
public string Version { get; set; }
}
要取用的地方 :
public class HomeController : Controller {
private readonly IOptions<AppsettingsOptions> _options;
public HomeController(IOptions<AppsettingsOptions> appSettings) {
_appSettings = appSettings;
}
public IActionResult Index() {
ViewData["AppName"] = _appSettings.Value.AppName;
ViewData["Version"] = _appSettings.Value.Version;
return View();
}
}
appsettings.json :
{
"AppSettings": {
"Demo":{
"AppName": "MyApplication",
"Version": "1.0.0"
}
}
}
創一個類別 :
public class AppsettingsOptions {
public const string AppSettings = "AppSettings";
public DemoOptions Demo { get; set; }
}
public class DemoOptions
{
public string AppName { get; set; }
public string Version { get; set; }
}
要取用的地方 :
public class HomeController : Controller {
private readonly IOptions<AppsettingsOptions> _options;
public HomeController(IOptions<AppsettingsOptions> appSettings) {
_appSettings = appSettings;
}
public IActionResult Index() {
ViewData["AppName"] = _appSettings.Value.Demo.AppName;
ViewData["Version"] = _appSettings.Value.Demo.Version;
return View();
}
}
必填、一些正規表達驗證等等都可以,但僅限於第一層,多層不適用,如下有附上一篇教學文章
public class AppsettingsOptions {
public const string AppSettings = "AppSettings";
[Required]
public string AppName { get; set; }
[Required]
public string Version { get; set; }
}
https://medium.com/@vijaykr100/options-pattern-in-asp-net-core-7121e7bd5054
簡單統整今日重點
今日結語
組態今天分享完畢,希望到目前為止已經對 ASP .NET Core 架構有更深入的了解
加油加油,明日繼續努力 ~