OptionsTest

Example #1: Simple options

Simple options implement IOptions(不能自动更新) with a MyOptions type: IOptions<MyOptions>. The options are registered as a service with the following code:


services.Configure<MyOptions>(Configuration);
                

option1 = value1s_from_json, option2 = -1

Simple options implement IOptionsMonitor(能自动更新) with a MyOptions type: IOptionsMonitor<MyOptions>. The options are registered as a service with the following code:


services.Configure<MyOptions>(Configuration);
                

option1 = value1s_from_json, option2 = -1

Example #2: Options configured by a delegate

Options can be configured by a delegate:


services.Configure<MyOptionsWithDelegateConfig>(myOptions =>
{
    myOptions.Option1 = "value1_configured_by_delegate";
    myOptions.Option2 = 500;
});
                

delegate_option1 = value1_configured_by_delegate, delegate_option2 = 500

Example #3: Suboptions

Suboptions specify the section of the configuration file to bind:


services.Configure<MySubOptions>(Configuration.GetSection("subsection"));
                

subOption1 = subvalue1_from_json, subOption2 = 200

Example #4: Model and injected options

Options provided by the model

Options provided by the model: @Model.MyOptions.Option1 and @Model.MyOptions.Option2

Option1: value1s_from_json

Option2: -1

Options injected into the page

Options injected into the page: @inject IOptionsMonitor<MyOptions> OptionsAccessor with @OptionsAccessor.CurrentValue.Option1 and @OptionsAccessor.CurrentValue.Option2

Option1: value1s_from_json

Option2: -1

Example #5: Snapshot options

Snapshot options are updated when the configuration is updated (the configuration file is saved). Modify the option1 and option2 values in the appsettings.json file. Save the file and refresh the page. The following snapshot options reflect the updated configuration:

snapshot option1 = value1s_from_json, snapshot option2 = -1

Example #6: Named options

Register ConfigurationBuilder instances which MyOptions binds against:


services.Configure<MyOptions>("named_options_1", Configuration);
                

A delegate can be used to configure named options:


services.Configure<MyOptions>("named_options_2", myOptions =>
{
    myOptions.Option1 = "named_options_2_value1_from_action";
});
                

named_options_1: option1 = value1s_from_json, option2 = -1 named_options_2: option1 = named_options_2_value1_from_action, option2 = 5