liveBook · Manning

IOptionsSnapshot<T>

As explained in ASP.NET Core in Action, 3e

IOptionsSnapshot<T> is a .NET options interface that provides options values capable of reflecting configuration changes across dependency-injection scopes.

IOptionsSnapshot<T> provides strongly typed access to a configuration section while allowing updated values to appear after configuration reloads. Unlike IOptions<T>, which is created once and keeps its original values, the snapshot creates a new options object when needed after the underlying configuration changes. section 10.3.2

Use IOptionsSnapshot<T> with these behaviors in mind:

  • Register options with Configure<T>() and bind the options class to a configuration section. section 10.3.1
  • Inject IOptionsSnapshot<T> through dependency injection and read the strongly typed settings from its Value property. section 10.3.2
  • Receive a snapshot-scoped service that is recreated for each request; after configuration reloads, later requests use newly bound option values. section 10.3.2
  • Avoid injecting it into singleton services because its scoped lifetime would create a captive dependency. section 10.3.2
  • Accept repeated binding costs when choosing reloadable options; use this approach only when the performance cost is acceptable. section 10.5

Expose current display settings

An endpoint can inject IOptionsSnapshot<AppDisplaySettings>, read options.Value, and return the current Title and ShowCopyright values. Editing the settings file and causing configuration to reload makes the updated values available on the next request. section 10.3.2

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains creation timing, dependency-injection lifetime, reload behavior, endpoint use, and performance tradeoffs.
Examples
Demonstrates an AppDisplaySettings endpoint that returns Title and ShowCopyright through options.Value.
What it assumes
Assumes configuration sections, POCO options classes, Configure<T>(), and dependency-injection lifetimes; teaches reloadable options behavior.
What you can do after
Apply it via dependency injection to serve updated configuration values on subsequent requests.
How it connects
Connects strongly typed options with configuration binding, dependency injection, IOptions<T>, IOptionsMonitor<T>, and configuration reloads.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.