Strongly typed options group related application settings in a C# class. ASP.NET Core binds configuration values to its properties, so a service can use settings.Title or settings.ShowCopyright instead of looking up string keys and parsing the results. Keeping each options class focused on one feature also makes services easier to test. section 10.3 section 10.3.1
Listing 10.6 Separating settings into different objects in appsettings.json
{
"MapSettings": { #1
"DefaultZoomLevel": 6, #1
"DefaultLocation": { #1
"latitude": 50.500, #1
"longitude": -4.000 #1
}
},
"AppDisplaySettings": { #2
"Title": "Acme Store Locator", #2
"ShowCopyright": true #2
}
}
The JSON example separates store-locator map settings from home-page display settings. Each section can be bound to its own options class. section 10.3
Use display settings in an endpoint
Define AppDisplaySettings with public Title (string) and ShowCopyright (bool) properties. In Program.cs, register it with builder.Services.Configure<AppDisplaySettings>(builder.Configuration.GetSection("AppDisplaySettings"));. An endpoint can then accept IOptions<AppDisplaySettings>, read options.Value, and use the typed properties. The binder converts the configuration value for ShowCopyright to bool. section 10.3.1 section 10.3
A few choices matter when setting this up:
- Use a nonabstract options class with a public parameterless constructor. The binder sets public properties whose names match configuration values; nested complex properties are supported. section 10.3.1
- Inject IOptions<T> when you want the standard options pattern. Its Value property exposes the configured object, but IOptions<T> does not refresh that value when configuration changes. Use IOptionsSnapshot<T> for per-request recreation when the repeated binding cost is acceptable. section 10.3.1 section 10.5
- For direct injection, bind a section to an object and register it in dependency injection, or register the Value of IOptions<T>. These approaches avoid an IOptions<T> dependency in consuming APIs but give up automatic options reloading without further work. section 10.3.4
Configuration providers can supply different values for different hosting environments while services continue to consume the same options class. Prefer this to checking the hosting environment throughout application services. section 10.4.2
