Net core Learning Series (X) - Net Core Configuration

I. Introduction

Option (the Options) model is an extension of the configuration (the Configuration) function. In Chapter 12 (configured in two ASP.NET Core) Configuration has introduced this feature (to bind the entity class, bound to the object graph, to bind an array class) and have the option mode option class (TOptions ), it refers to the action category option: to associate properties with a source of configuration options in a key class. For Example, assuming there Option1 json file keys, also a man named option class property name Option1, through configuration options, so that the value can be mapped to the key json option class attribute values. It is also understood in the application program, the sequence of a file to .net json class.

Second, the conventional configuration options

Non-abstract class option class must contain a public no-argument constructor. Add option1 in appsettings.json file, option2, subsection configuration:

Copy the code
{
  "option1": "value1_from_json", "option2": -1, "subsection": { "suboption1": "subvalue1_from_json", "suboption2": 200 }, "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*" }
Copy the code

MyOptions new class (Models / MyOptions.cs), the following classes MyOptions has three attributes: Option1 and Option2. The default setting is optional, but the class constructor is provided the following example of default values ​​Option1. Option2 initialized with default values ​​by a direct property settings:

Copy the code
public class MyOptions
{
    public MyOptions()
    {
        // Set default value. Option1 = "value1_from_ctor"; } public string Option1 { get; set; } public int Option2 { get; set; } = 5; }
Copy the code

The MyOptions class added to the service container by Configure and bind to the configuration:

Copy the code
public void ConfigureServices(IServiceCollection services)
{
    // Example #1: General configuration
    // Register the Configuration instance which MyOptions binds against. services.Configure<MyOptions>(Configuration); }
Copy the code

You can also use custom ConfigurationBuilder when loading configuration options from the Settings file, make sure the base path is set correctly, added to the service container and bind to the configuration:

var configBuilder = new ConfigurationBuilder()
   .SetBasePath(Directory.GetCurrentDirectory())
   .AddJsonFile("appsettings.json", optional: true); var config = configBuilder.Build(); services.Configure<MyOptions>(config);

The following pages model by IOptionsMonitor <TOptions> using the constructor dependency injection to access settings (Pages / Index.cshtml.cs):

Copy the code
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}"; } }
Copy the code

IndexModel.OnGet method call returns a string containing the option value in the Home / Index Controller Action:

Copy the code
public HomeController(IOptionsMonitor<MyOptions> optionsAccessor)
{
    _optionsAccessor = optionsAccessor;
}
private readonly IOptionsMonitor<MyOptions> _optionsAccessor; public IActionResult Index() { IndexModel indexModel = new IndexModel(_optionsAccessor); indexModel.OnGet(); return View(); }
Copy the code

Third, commissioned by simple configuration options

Use delegation settings option value. This sample application uses the new class MyOptionsWithDelegateConfig (Models / MyOptionsWithDelegateConfig.cs):

Copy the code
public class MyOptionsWithDelegateConfig
{
    public MyOptionsWithDelegateConfig()
    {
        // Set default value. Option1 = "value1_from_ctor"; } public string Option1 { get; set; } public int Option2 { get; set; } = 5; }
Copy the code

Add IConfigureOptions <TOptions> container services to the service. MyOptionsWithDelegateConfig it to configure bindings by using delegates:

Copy the code
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; }); }
Copy the code

The following pages model by IOptionsMonitor <TOptions> using the constructor dependency injection to access settings (Pages / Index.cshtml.cs):

Copy the code
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}"; } }
Copy the code

在Home/Index控制器Action下调用IndexModel.OnGet方法返回包含选项值的字符串:

Copy the code
public HomeController(IOptionsMonitor<MyOptionsWithDelegateConfig> optionsAccessorWithDelegateConfig)
{
    _optionsAccessorWithDelegateConfig = optionsAccessorWithDelegateConfig;
}
private readonly IOptionsMonitor<MyOptionsWithDelegateConfig> _optionsAccessorWithDelegateConfig; public IActionResult Index() { IndexModel indexModel = new IndexModel(_optionsAccessorWithDelegateConfig); indexModel.OnGet(); return View(); }
Copy the code


每次调用Configure都会将IConfigureOptions<TOptions>服务添加到服务容器。在前面的示例中,Option1和Option2的值同时在appsettings.json中指定,但Option1和Option2的值被配置的委托替代。当启用多个配置服务时,指定的最后一个配置源优于其他源,由其设置配置值。运行应用程序时,页面模型的OnGet方法返回显示选项类值的字符串。

四、子选项配置

将选项绑定到配置时,选项类型中的每个属性都将绑定到窗体property[:sub-property:]的配置键。例如,MyOptions.Option1属性将绑定到从appsettings.json中的option1属性读取的键Option1。在以下代码中,已向服务容器添加IConfigureOptions<TOptions>服务。它将MySubOptions绑定到appsettings.json文件的subsection部分:

Copy the code
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")); }
Copy the code

新建MySubOptions类(Models/MySubOptions.cs)将属性SubOption1和SubOption2定义为保留选项值:

Copy the code
public class MySubOptions
{
    public MySubOptions()
    {
        // Set default values. SubOption1 = "value1_from_ctor"; SubOption2 = 5; } public string SubOption1 { get; set; } public int SubOption2 { get; set; } }
Copy the code

以下页面模型通过IOptionsMonitor<TOptions>使用构造函数依赖关系注入来访问设置(Pages/Index.cshtml.cs):

Copy the code
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}"; } }
Copy the code

在Home/Index控制器Action下调用IndexModel.OnGet方法返回包含选项值的字符串:

Copy the code
public HomeController(IOptionsMonitor<MySubOptions> subOptionsAccessor)
{
    _subOptionsAccessor = subOptionsAccessor;
}
private readonly IOptionsMonitor<MySubOptions> _subOptionsAccessor; public IActionResult Index() { IndexModel indexModel = new IndexModel(_subOptionsAccessor); indexModel.OnGet(); return View(); }
Copy the code

五、通过IOptionsSnapshot重新加载配置数据

IOptionsSnapshot针对请求生命周期访问和缓存选项时,每个请求只能计算一次选项。以下示例演示如何在更改appsettings.json(Pages/Index.cshtml.cs)后创建新的 IOptionsSnapshot<TOptions>。在更改appsettings.json文件和重新加载配置之前,针对服务器的多个请求返回appsettings.json文件提供的配置键值。

Copy the code
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}"; } }
Copy the code

下面显示从appsettings.json文件加载的初始option1和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

六、包含IConfigureNamedOptions的命名选项支持

命名选项支持允许应用程序在命名选项配置之间进行区分。命名选项通过OptionsServiceCollectionExtensions.Configure进行声明,其调用扩展方法ConfigureNamedOptions<TOptions>.Configure:

Copy the code
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"; }); }
Copy the code

通过OnGet(Pages/Index.cshtml.cs)访问命名选项:

Copy the code
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}"; } }
Copy the code

在Home/Index控制器Action下调用IndexModel.OnGet方法返回包含选项值的字符串:

Copy the code
public HomeController(IOptionsSnapshot<MyOptions> namedOptionsAccessor)
{
    _namedOptionsAccessor = namedOptionsAccessor;
}
private readonly IOptionsSnapshot<MyOptions> _namedOptionsAccessor; public IActionResult Index() { IndexModel indexModel = new IndexModel(_namedOptionsAccessor); indexModel.OnGet(); return View(); }
Copy the code

七、使用ConfigureAll方法配置所有选项

使用ConfigureAll方法可以配置所有选项实例。以下代码将针对包含公共值的所有配置实例配置Option1。将以下代码手动添加到Startup.ConfigureServices方法:

services.ConfigureAll<MyOptions>(myOptions =>
{
    myOptions.Option1 = "ConfigureAll replacement value";
});

IndexModel.OnGet method call returns a string containing the option value in the Home / Index Controller Action:

Reference: https://www.cnblogs.com/lonelyxmas/p/10302449.html

Guess you like

Origin www.cnblogs.com/wyh19941210/p/11516550.html