liveBook · Manning

Options pattern

As explained in Pro ASP.NET Core 7, Tenth Edition

The options pattern is a .NET configuration pattern that represents related settings in classes and registers those settings for access through dependency injection.

The options pattern keeps related ASP.NET Core settings in a class and makes them available through dependency injection. It is commonly used to configure middleware. Define properties with defaults, then register changes with `builder.Services.Configure<TOptions>(...)` before calling `builder.Build()`. section 12.5

Listing 12.16 Using the options pattern in the Program.cs file in the Platform folder
using Microsoft.Extensions.Options;
using Platform;

var builder = WebApplication.CreateBuilder(args);

builder.Services.Configure<MessageOptions>(options => {
    options.CityName = "Albany";
});

var app = builder.Build();

app.MapGet("/location", async (HttpContext context,
    IOptions<MessageOptions> msgOpts) => {
        Platform.MessageOptions opts = msgOpts.Value;
        await context.Response.WriteAsync($"{opts.CityName}, " 
            + opts.CountryName);
    });
        
app.MapGet("/", () => "Hello World!");

app.Run();

A complete `Program.cs` example changes `MessageOptions.CityName` to `Albany`, then reads the registered options at `/location`. section 12.5

The `/location` handler receives `IOptions<MessageOptions>` as a parameter and reads its `Value`. With `CountryName` left at its default, the response is `Albany, USA`. Class-based middleware can instead receive `IOptions<MessageOptions>` in its constructor; `UseMiddleware<LocationMiddleware>()` resolves that parameter, and `Invoke` uses the settings while processing requests. section 12.5 section 12.5.1

Options can also come from configuration rather than a configuration callback. Pass `builder.Configuration.GetSection("Location")` to `Configure<MessageOptions>`; matching configuration keys replace property defaults. If `appsettings.json` sets only `Location:CityName` to `Buffalo`, `/location` uses `Buffalo` and retains the class’s default `CountryName`. section 15.2.4

The same approach configures other ASP.NET Core features:

  • Set session idle time and cookie settings with `AddSession(opts => ...)`, then add `UseSession()` to the pipeline. A nonessential session cookie can cause trouble when cookie consent applies. section 16.3.1
  • Add a Razor Page route with `Configure<RazorPagesOptions>` and `opts.Conventions.AddPageRoute(...)`; the added URL supplements the page’s existing route. section 23.3.2
  • Change Identity’s login and access-denied redirect paths through named `CookieAuthenticationOptions` for the application scheme. section 39.3.5

How Pro ASP.NET Core 7, Tenth Edition covers it

How deep it goes
Works through registration, endpoint and constructor injection, and configuration-section binding; defers a detailed account of dependency injection.
Examples
Shows a location endpoint, class-based middleware, JSON-backed settings, session setup, an extra page route, and authentication redirects.
What it assumes
Assumes familiarity with C# application setup and middleware; introduces options registration while deferring dependency injection details.
What you can do after
Operate/configure ASP.NET Core features by registering options, supplying configuration values, and reading them through `IOptions<T>`.
How it connects
Connects dependency injection, middleware, `IConfiguration`, session cookies, Razor Pages routing, and cookie authentication.

Also explained in

Compare how 2 books explain options pattern →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Pro ASP.NET Core 7, Tenth Edition. The section links point to the parts of the book it draws on.