您好,登錄后才能下訂單哦!
這篇文章主要介紹“ASP.NET Core中的Options選項模式怎么配置”的相關(guān)知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強(qiáng),希望這篇“ASP.NET Core中的Options選項模式怎么配置”文章能幫助大家解決問題。
選項(Options)模式是對配置(Configuration)的功能的延伸。在12章(ASP.NET Core中的配置二)Configuration中有介紹過該功能(綁定到實體類、綁定至對象圖、將數(shù)組綁定至類)而選項模式又有個選項類(TOptions),該選項類作用是指:把選項類中的屬性與配置來源中的鍵關(guān)聯(lián)起來。舉個例,假設(shè)json文件有個Option1鍵,選項類中也有個叫Option1的屬性名,經(jīng)過選項配置,這樣就能把json中的鍵的值映射到選項類屬性值中。也可以理解在項目應(yīng)用中,把一個json文件序列化到.net類。
選項類必須為包含公共無參數(shù)構(gòu)造函數(shù)的非抽象類。在appsettings.json文件中添加option1、option2、subsection的配置:
{ "option1": "value1_from_json", "option2": -1, "subsection": { "suboption1": "subvalue1_from_json", "suboption2": 200 }, "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*" }
新建MyOptions類(Models/MyOptions.cs),以下類MyOptions具有三種屬性:Option1和 Option2。設(shè)置默認(rèn)值為可選,但以下示例中的類構(gòu)造函數(shù)設(shè)置了Option1的默認(rèn)值。Option2具有通過直接初始化屬性設(shè)置的默認(rèn)值:
public class MyOptions { public MyOptions() { // Set default value. Option1 = "value1_from_ctor"; } public string Option1 { get; set; } public int Option2 { get; set; } = 5; }
而MyOptions類通過Configure添加到服務(wù)容器并綁定到配置:
public void ConfigureServices(IServiceCollection services) { // Example #1: General configuration // Register the Configuration instance which MyOptions binds against. services.Configure<MyOptions>(Configuration); }
也可以使用自定義ConfigurationBuilder從設(shè)置文件加載選項配置時,確認(rèn)基路徑設(shè)置正確,添加到服務(wù)容器并綁定到配置:
var configBuilder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true); var config = configBuilder.Build(); services.Configure<MyOptions>(config);
以下頁面模型通過IOptionsMonitor<TOptions>使用構(gòu)造函數(shù)依賴關(guān)系注入來訪問設(shè)置 (Pages/Index.cshtml.cs):
public class IndexModel { public IndexModel(IOptionsMonitor<MyOptions> optionsAccessor) { _options = optionsAccessor.CurrentValue; } private readonly MyOptions _options; public void OnGet() { // Example #1: Simple options var option1 = _options.Option1; var option2 = _options.Option2; var simpleOptions = $"option1 = {option1}, option2 = {option2}"; } }
在Home/Index控制器Action下調(diào)用IndexModel.OnGet方法返回包含選項值的字符串:
public HomeController(IOptionsMonitor<MyOptions> optionsAccessor) { _optionsAccessor = optionsAccessor; } private readonly IOptionsMonitor<MyOptions> _optionsAccessor; public IActionResult Index() { IndexModel indexModel = new IndexModel(_optionsAccessor); indexModel.OnGet(); return View(); }
使用委托設(shè)置選項值。此示例應(yīng)用程序使用新建MyOptionsWithDelegateConfig類 (Models/MyOptionsWithDelegateConfig.cs):
public class MyOptionsWithDelegateConfig { public MyOptionsWithDelegateConfig() { // Set default value. Option1 = "value1_from_ctor"; } public string Option1 { get; set; } public int Option2 { get; set; } = 5; }
向服務(wù)容器添加IConfigureOptions<TOptions>服務(wù)。它通過MyOptionsWithDelegateConfig使用委托來配置綁定:
public void ConfigureServices(IServiceCollection services) { // Example #2: Options bound and configured by a delegate services.Configure<MyOptionsWithDelegateConfig>(myOptions => { myOptions.Option1 = "value1_configured_by_delegate"; myOptions.Option2 = 500; }); }
以下頁面模型通過IOptionsMonitor<TOptions>使用構(gòu)造函數(shù)依賴關(guān)系注入來訪問設(shè)置 (Pages/Index.cshtml.cs):
public class IndexModel { private readonly MyOptionsWithDelegateConfig _optionsWithDelegateConfig; public IndexModel(IOptionsMonitor<MyOptionsWithDelegateConfig> optionsAccessorWithDelegateConfig) { _optionsWithDelegateConfig = optionsAccessorWithDelegateConfig.CurrentValue; } public void OnGet() { // Example #2: Options configured by delegate var delegate_config_option1 = _optionsWithDelegateConfig.Option1; var delegate_config_option2 = _optionsWithDelegateConfig.Option2; var simpleOptionsWithDelegateConfig = $"delegate_option1 = {delegate_config_option1}, " + $"delegate_option2 = {delegate_config_option2}"; } }
在Home/Index控制器Action下調(diào)用IndexModel.OnGet方法返回包含選項值的字符串:
public HomeController(IOptionsMonitor<MyOptionsWithDelegateConfig> optionsAccessorWithDelegateConfig) { _optionsAccessorWithDelegateConfig = optionsAccessorWithDelegateConfig; } private readonly IOptionsMonitor<MyOptionsWithDelegateConfig> _optionsAccessorWithDelegateConfig; public IActionResult Index() { IndexModel indexModel = new IndexModel(_optionsAccessorWithDelegateConfig); indexModel.OnGet(); return View(); }
每次調(diào)用Configure都會將IConfigureOptions<TOptions>服務(wù)添加到服務(wù)容器。在前面的示例中,Option1和Option2的值同時在appsettings.json中指定,但Option1和Option2的值被配置的委托替代。當(dāng)啟用多個配置服務(wù)時,指定的最后一個配置源優(yōu)于其他源,由其設(shè)置配置值。運行應(yīng)用程序時,頁面模型的OnGet方法返回顯示選項類值的字符串。
將選項綁定到配置時,選項類型中的每個屬性都將綁定到窗體property[:sub-property:]的配置鍵。例如,MyOptions.Option1屬性將綁定到從appsettings.json中的option1屬性讀取的鍵Option1。在以下代碼中,已向服務(wù)容器添加IConfigureOptions<TOptions>服務(wù)。它將MySubOptions綁定到appsettings.json文件的subsection部分:
public void ConfigureServices(IServiceCollection services) { // Example #3: Suboptions // Bind options using a sub-section of the appsettings.json file. services.Configure<MySubOptions>(Configuration.GetSection("subsection")); }
新建MySubOptions類(Models/MySubOptions.cs)將屬性SubOption1和SubOption2定義為保留選項值:
public class MySubOptions { public MySubOptions() { // Set default values. SubOption1 = "value1_from_ctor"; SubOption2 = 5; } public string SubOption1 { get; set; } public int SubOption2 { get; set; } }
以下頁面模型通過IOptionsMonitor<TOptions>使用構(gòu)造函數(shù)依賴關(guān)系注入來訪問設(shè)置(Pages/Index.cshtml.cs):
public class IndexModel { private readonly MySubOptions _subOptions; public IndexModel(IOptionsMonitor<MySubOptions> subOptionsAccessor) { _subOptions = subOptionsAccessor.CurrentValue; } public void OnGet() { // Example #3: Suboptions var subOption1 = _subOptions.SubOption1; var subOption2 = _subOptions.SubOption2; var subOptions = $"subOption1 = {subOption1}, subOption2 = {subOption2}"; } }
在Home/Index控制器Action下調(diào)用IndexModel.OnGet方法返回包含選項值的字符串:
public HomeController(IOptionsMonitor<MySubOptions> subOptionsAccessor) { _subOptionsAccessor = subOptionsAccessor; } private readonly IOptionsMonitor<MySubOptions> _subOptionsAccessor; public IActionResult Index() { IndexModel indexModel = new IndexModel(_subOptionsAccessor); indexModel.OnGet(); return View(); }
IOptionsSnapshot針對請求生命周期訪問和緩存選項時,每個請求只能計算一次選項。以下示例演示如何在更改appsettings.json(Pages/Index.cshtml.cs)后創(chuàng)建新的 IOptionsSnapshot<TOptions>。在更改appsettings.json文件和重新加載配置之前,針對服務(wù)器的多個請求返回appsettings.json文件提供的配置鍵值。
public class IndexModel { private readonly MyOptions _snapshotOptions; public IndexModel(IOptionsSnapshot<MyOptions> snapshotOptionsAccessor) { _snapshotOptions = snapshotOptionsAccessor.Value; } public void OnGet() { // Example #5: Snapshot options var snapshotOption1 = _snapshotOptions.Option1; var snapshotOption2 = _snapshotOptions.Option2; var snapshotOptions = $"snapshot option1 = {snapshotOption1}, " + $"snapshot option2 = {snapshotOption2}"; } }
下面顯示從appsettings.json文件加載的初始o(jì)ption1和option2值:
snapshot option1 = value1_from_json, snapshot option2 = -1
將appsettings.json文件中的值更改為value1_from_json UPDATED和200。保存appsettings.json 文件。刷新瀏覽器,查看更新的選項值:
snapshot option1 = value1_from_json UPDATED, snapshot option2 = 200
命名選項支持允許應(yīng)用程序在命名選項配置之間進(jìn)行區(qū)分。命名選項通過OptionsServiceCollectionExtensions.Configure進(jìn)行聲明,其調(diào)用擴(kuò)展方法ConfigureNamedOptions<TOptions>.Configure:
public void ConfigureServices(IServiceCollection services) { // Example #6: Named options (named_options_1) // Register the ConfigurationBuilder instance which MyOptions binds against. // Specify that the options loaded from configuration are named // "named_options_1". services.Configure<MyOptions>("named_options_1", Configuration); // Example #6: Named options (named_options_2) // Specify that the options loaded from the MyOptions class are named // "named_options_2". // Use a delegate to configure option values. services.Configure<MyOptions>("named_options_2", myOptions => { myOptions.Option1 = "named_options_2_value1_from_action"; }); }
通過OnGet(Pages/Index.cshtml.cs)訪問命名選項:
public class IndexModel { private readonly MyOptions _named_options_1; private readonly MyOptions _named_options_2; public IndexModel(IOptionsSnapshot<MyOptions> namedOptionsAccessor) { _named_options_1 = namedOptionsAccessor.Get("named_options_1"); _named_options_2 = namedOptionsAccessor.Get("named_options_2"); } public void OnGet() { // Example #6: Named options var named_options_1 = $"named_options_1: option1 = {_named_options_1.Option1}, " + $"option2 = {_named_options_1.Option2}"; var named_options_2 = $"named_options_2: option1 = {_named_options_2.Option1}, " + $"option2 = {_named_options_2.Option2}"; var namedOptions = $"{named_options_1} {named_options_2}"; } }
在Home/Index控制器Action下調(diào)用IndexModel.OnGet方法返回包含選項值的字符串:
public HomeController(IOptionsSnapshot<MyOptions> namedOptionsAccessor) { _namedOptionsAccessor = namedOptionsAccessor; } private readonly IOptionsSnapshot<MyOptions> _namedOptionsAccessor; public IActionResult Index() { IndexModel indexModel = new IndexModel(_namedOptionsAccessor); indexModel.OnGet(); return View(); }
使用ConfigureAll方法可以配置所有選項實例。以下代碼將針對包含公共值的所有配置實例配置Option1。將以下代碼手動添加到Startup.ConfigureServices方法:
services.ConfigureAll<MyOptions>(myOptions => { myOptions.Option1 = "ConfigureAll replacement value"; });
在Home/Index控制器Action下調(diào)用IndexModel.OnGet方法返回包含選項值的字符串:
關(guān)于“ASP.NET Core中的Options選項模式怎么配置”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。