什么时候使用 ASP.NET 5 OptionsModel?

When to use ASP.NET 5 OptionsModel?

在我通过 ASP.NET 胆量进行调查的过程中,我发现了其中一些有趣的部分 - OptionsModel

Startup中定义的示例代码class:

// Add MVC services to the services container
services.AddMvc(configuration)
    .Configure<MvcOptions>(options =>
    {
        //Configure some MVC options like customizing the 
        // view engines, etc...
        options.ViewEngines.Insert(0, typeof(TestViewEngine));
    });

还有几个问题:

  1. 在您自己的解决方案中使用 OptionsModel 的最佳方式是什么?
  2. 它比 SettingsModel 好在哪里?

我看到它们之间的区别,但想找到最佳用例。

来自asp.net docs

Using Options you can easily convert any class (or POCO - Plain Old CLR Object) into a settings class. It’s recommended that you create well-factored settings objects that correspond to certain features within your application, thus following the Interface Segregation Principle (ISP) (classes depend only on the configuration settings they use) as well as Separation of Concerns (settings for disparate parts of your app are managed separately, and thus are less likely to negatively impact one another).

因此您可以创建任何 POCO class 作为您的选择 class:

public class MyOptions
{
    public string Option1 { get; set; }
    public int Option2 { get; set; }
}

然后为您的应用程序启用选项服务(添加 MVC 服务时 already done):

//In your ConfigureServices method
services.AddOptions();

这允许您在需要访问您的选项的任何 class 上注入 IOptions<YourOptionsClass>

public HomeController(IOptions<MyOptions> optionsAccessor)
{
    Options = optionsAccessor.Options;
}

最后一个难题是如何配置(提供值)您的选项。

  • 最明显的方法是使用新的 Configuration 框架,例如您可以使用 config.json 文件(您不需要创建新的配置对象,您可以重复使用 MVC 应用程序模板默认添加的相同模板)。获得配置对象后,您可以调用 Configure<YourOptionsClass>(Configuration):

    Note: When you bind options to configuration each property in your options type is bound to a configuration key of the form property:subproperty:etc, which are case insensitive.

    //In your Startup method
    MyConfig = new ConfigurationBuilder()
                    .SetBasePath(appEnv.ApplicationBasePath)
                    .AddJsonFile("appsettings.json")
                    .Build();
    
    //In your ConfigureServices method
    services.Configure<MyOptions>(Configuration);
    
  • 您还可以使用委托并通过 运行 所需的任何代码段来初始化您的选项。例如,你可以提供一些硬编码值(但你也可以做一些更复杂的事情,比如从数据库中读取):

    services.Configure<MyOptions>(myOptions =>
    {
        myOptions.Option1 = "Foo";
        myOptions.Option2 = 42;
    });
    

您可以添加多个 Configure<MyOptions> 调用,它们将按顺序应用。例如,您可以提供一些硬编码值并允许使用配置覆盖它们:

services.Configure<MyOptions>(myOptions =>
{
    ...
})
.Configure<MyOptions>(Configuration);

最后,在 Configuration and the Options 框架之间,您有一种灵活、可扩展、可组合且松散耦合的方式来提供您的代码可能需要的设置。