liveBook · Manning

AddOptions<T>()

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

AddOptions<T>() is an ASP.NET Core service-collection extension method that creates an OptionsBuilder<T> for configuring an options type.

AddOptions<T>() creates an OptionsBuilder<T> in the ASP.NET Core service collection. The builder lets you configure a strongly typed options object with fluent calls such as BindConfiguration() and Configure(). section 31.2 section 31.4

Build an options configuration in layers:

  • Call Configure() to apply additional values or use Configure<TDep>() to receive dependencies from the DI container. section 31.2
  • Add validation when configuration must be checked as the options object is loaded. section 31.2

Configure currency options

WebApplicationBuilder builder = WebApplication.CreateBuilder(args); builder.Services .AddOptions<CurrencyOptions>() .BindConfiguration("Currencies") .Configure(opts => opts.Currencies = new string[] { "GBP", "USD" }); WebApplication app = builder.Build(); app.MapGet("/", (IOptions<CurrencyOptions> opts) => opts.Value); app.Run(); The service collection registers the builder configuration, and resolving IOptions<CurrencyOptions> produces the configured value.

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

How deep it goes
Explains builder creation, chained binding, lambda configuration, dependency injection, and validation without detailing framework internals.
Examples
Demonstrates CurrencyOptions bound to the Currencies section and supplemented with GBP and USD values.
What it assumes
Assumes familiarity with ASP.NET Core service registration, IConfiguration, dependency injection, and IOptions<T>.
What you can do after
Apply it via ASP.NET Core dependency injection to build and retrieve configured IOptions<T> values.
How it connects
Connects OptionsBuilder<T> with IOptions<T>, IConfiguration, dependency injection, and IConfigureOptions<T>.

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.