How to use the IOptions pattern for configuration in ASP

Ioptions snapshot

Ioptions snapshot


Named options support allows the app to distinguish between named options configurations. In the sample app, named options are declared with , which calls the ConfigureNamedOptions extension method. Named options are case sensitive.

Hot Swapping Custom Configurations in Core Using

When binding options to configuration, each property in the options type is bound to a configuration key of the form property[:sub-property:]. For example, the property is bound to the key Option6 , which is read from the option6 property in .

IOptions, IOptions monitor, and IOptions snapshot

In Core, there is now no default AppSettings[ MySettingKey ] way to get settings. Instead, the recommended approach is to create a strongly typed configuration class with a structure that matches a section in your configuration file (or wherever your configuration is being loaded from):

GitHub - Ibro/AspNetCoreConfiguration: Core

Apps should create options classes that pertain to specific scenario groups (classes) in the app. Parts of the app that require configuration values should only have access to the configuration values that they use.

.NET Core Options

We recommend passing a configuration delegate to Configure , since creating a service is more complex. Creating your own type is equivalent to what the framework does for you when you use Configure. Calling Configure registers a transient generic IConfigureNamedOptions TOptions , which has a constructor that accepts the generic service types specified.

OptionsBuilder TOptions is used to configure TOptions instances. OptionsBuilder streamlines creating named options as it's only a single parameter to the initial AddOptions TOptions (string optionsName) call instead of appearing in all of the subsequent calls. Options validation and the ConfigureOptions overloads that accept service dependencies are only available via OptionsBuilder.

IOptionsMonitorCache TOptions is used by IOptionsMonitor TOptions to cache TOptions instances. The IOptionsMonitorCache TOptions invalidates options instances in the monitor so that the value is recomputed ( TryRemove ). Values can be manually introduced with TryAdd. The Clear method is used when all named instances should be recreated on demand.

In a previous article we went over how to read custom configurations into memory in Core. This is also the new way to do Appsettings. But did you know that you can also do 8775 hot loading 8776 of configurations? That is, while your app is running, you can change an appsetting or configuration and your application will reload it on the fly without an app pool recycle or restarting the web server? Pretty nifty! Let 8767 s take a look.

I have class AbClass that get with core built-in DI instance of IOptionsSnapshot AbOptions (dynamic configuration). now I want to test this class.


Leave a comment