AspNetCore.Docs/aspnetcore/includes/bind.md

2.7 KiB

The preferred way to read related configuration values is using the options pattern. For example, to read the following configuration values:

  "Position": {
    "Title": "Editor",
    "Name": "Joe Smith"
  }

Create the following PositionOptions class:

[!code-csharp]

An options class:

  • Must be non-abstract with a public parameterless constructor.
  • All public read-write properties of the type are bound.
  • Fields are not bound. In the preceding code, Position is not bound. The Position property is used so the string "Position" doesn't need to be hard coded in the app when binding the class to a configuration provider.

The following code:

  • Calls ConfigurationBinder.Bind to bind the PositionOptions class to the Position section.
  • Displays the Position configuration data.

[!code-csharp]

In the preceding code, by default, changes to the JSON configuration file after the app has started are read.

ConfigurationBinder.Get<T> binds and returns the specified type. ConfigurationBinder.Get<T> may be more convenient than using ConfigurationBinder.Bind. The following code shows how to use ConfigurationBinder.Get<T> with the PositionOptions class:

[!code-csharp]

In the preceding code, by default, changes to the JSON configuration file after the app has started are read.

An alternative approach when using the options pattern is to bind the Position section and add it to the dependency injection service container. In the following code, PositionOptions is added to the service container with xref:Microsoft.Extensions.DependencyInjection.OptionsConfigurationServiceCollectionExtensions.Configure* and bound to configuration:

[!code-csharp]

Using the preceding code, the following code reads the position options:

[!code-csharp]

In the preceding code, changes to the JSON configuration file after the app has started are not read. To read changes after the app has started, use IOptionsSnapshot.