The options pattern uses classes to represent groups of related settings. When configuration settings are isolated by scenario into separate classes, the app adheres to two important software engineering principles:
- The Interface Segregation Principle (ISP): Scenarios (classes) that depend on configuration settings depend only on the configuration settings that they use.
- Separation of Concerns: Settings for different parts of the app aren't dependent or coupled to one another.
Reference the Microsoft.AspNetCore.App metapackage or add a package reference to the Microsoft.Extensions.Options.ConfigurationExtensions package.
Basic options configuration
Basic options configuration is demonstrated as Example #1 in the sample app.
An options class must be non-abstract with a public parameterless constructor. The following class,
MyOptions, has two properties,
Option2. Setting default values is optional, but the class constructor in the following example sets the default value of
Option2 has a default value set by initializing the property directly (Models/MyOptions.cs):
MyOptions class is added to the service container with Configure<TOptions>(IServiceCollection, IConfiguration) and bound to configuration:
The sample's appsettings.json file specifies values for
When the app is run, the page model's
OnGet method returns a string showing the option class values: