A configuration binder maps configuration values to a strongly typed object, often called an options class. It replaces repeated string lookups and manual parsing with typed properties, IntelliSense, and runtime conversion. section 10.3
Binding settings for an endpoint
Separate configuration under MapSettings and AppDisplaySettings, then inject IOptions<AppDisplaySettings>. The handler reads options.Value and returns settings.Title and settings.ShowCopyright without dictionary keys or bool.Parse calls. section 10.3
Design options classes so the binder can construct and populate them:
- Use a nonabstract class with a public parameterless constructor. section 10.3.3
- Expose public properties with getters and setters; complex properties need a setter or a non-null value. section 10.3.3
- Use collections carefully: common list and dictionary interfaces can be created automatically, but initialized IEnumerable properties cannot be replaced. section 10.3.3
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
}
}
Use nested configuration sections to keep settings for different application areas in separate strongly typed objects. section 10.3
IOptions<T> is the canonical integration, but the binder can also bind a configuration section manually, register the resulting object as a singleton, and inject that object directly. This avoids the IOptions<T>.Value step but gives up automatic reload behavior and advanced options features unless added separately. section 10.3.4
