📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is the options pattern in ASP.NET Core? Show how you bind a configuration section to a class with Configure<T> or AddOptions<T>().BindConfiguration(), explain how the binder maps keys to properties, and tell me why you shouldn't inject IConfiguration everywhere.

The options pattern: binding configuration sections to strongly typed classes with Configure<T>, AddOptions<T>().Bind/BindConfiguration, how ConfigurationBinder maps keys to properties (case-insensitive, conversions, collections, missing keys, ErrorOnUnknownConfiguration), IConfigureOptions and PostConfigure for code-based setup, the binding source generator for AOT, and why injecting IConfiguration into services is an anti-pattern.

Intermediate Theory Intermediate aspnet-core configuration dependency-injection ioptions options-pattern

🎯 Key points

  • Options pattern = bind a configuration section to a POCO once and inject IOptions<T> (or snapshot/monitor) instead of IConfiguration
  • AddOptions<T>().BindConfiguration("Section") is the modern form; Configure<T>(section) is the older equivalent
  • ConfigurationBinder matches keys to public properties case-insensitively and converts strings with TypeConverter, invariant culture
  • Missing keys leave property defaults; bad conversions throw at bind time; ErrorOnUnknownConfiguration catches typos
  • Chain ValidateDataAnnotations/Validate/ValidateOnStart so bad config fails at start-up, not on the first request
  • IConfigureOptions<T> and PostConfigure set values that need other services or computed defaults
  • EnableConfigurationBindingGenerator (on automatically with Native AOT) replaces the reflection binder
  • Injecting IConfiguration spreads magic strings, hides dependencies and skips validation

⏱ 30-second answer

The options pattern binds a configuration section to a strongly typed class once, at the composition root, and injects IOptions<T> (or IOptionsSnapshot<T> / IOptionsMonitor<T>) where it is needed. You register it with builder.Services.AddOptions<PaymentOptions>().BindConfiguration("Payments"), usually chained with ValidateDataAnnotations().ValidateOnStart().

The ConfigurationBinder matches keys to public properties case-insensitively and converts strings to the property type; missing keys leave defaults.

Injecting IConfiguration everywhere instead spreads magic strings, hides what a class really depends on, makes tests build fake configuration, and skips validation. The trade-off: one small class and a registration per section, in exchange for typed, validated, discoverable settings.

🗣 Full answer (senior)

How I would answer this in an interview

"The options pattern is how I turn configuration into typed objects. I write a class like PaymentOptions with the properties of a section, register it once with AddOptions<PaymentOptions>().BindConfiguration("Payments"), and services take IOptions<PaymentOptions> in their constructor. The binder walks the section, matches keys to properties case-insensitively, converts the strings, "00:00:10" to a TimeSpan, "3" to an int, and fills lists and dictionaries from child sections. Keys that are missing leave the property's default, which is why I give every property a sensible default in the class.

I always chain validation: ValidateDataAnnotations() for simple rules and ValidateOnStart() so the app refuses to start with a missing API key instead of failing on the first payment. When a value depends on another service or needs computing, I use IConfigureOptions<T> or PostConfigure, which still produces the same options object. For Native AOT the reflection binder isn't trim-safe, so the configuration binding source generator takes over.

Why not just inject IConfiguration? Because config["Payments:Timout"] with a typo returns null at run time and nothing tells you. The class signature no longer says what it needs, a unit test has to build a fake configuration tree, and there is nowhere to hang validation. The mistake I see is the halfway house: binding with GetSection().Get<T>() inside a constructor on every resolve. Options gives you one place that defines the shape of a section, one place that validates it, and constructors that tell the truth."


Ways to register

Registration Notes
services.AddOptions<T>().BindConfiguration("Section") Preferred; returns an OptionsBuilder<T> for chaining validation
services.AddOptions<T>().Bind(config.GetSection("Section")) Same, when you already have a section
services.Configure<T>(config.GetSection("Section")) Older style, no builder to chain
services.Configure<T>(o => o.Retries = 3) Code-only values
services.ConfigureOptions<MyConfigureOptions>() IConfigureOptions<T> that can use injected services
services.PostConfigure<T>(o => ...) Runs after all Configure calls: computed defaults

How the binder maps values

Configuration Property Result
Payments:Timeout = "00:00:10" TimeSpan Timeout 10 seconds
Payments:Regions:0, :1 List<string> Regions Two items
Payments:Fees:AUD = "0.3" Dictionary<string, decimal> Fees { AUD: 0.3 }
key missing int Retries { get; init; } = 3 Stays 3
Payments:Retries = "three" int Retries InvalidOperationException when bound
Payments:Retires = 5 (typo) Ignored, unless ErrorOnUnknownConfiguration = true

Production example

A payments service had 23 config["..."] reads across 11 classes. Two had typos that returned null and fell back to hard-coded values nobody remembered. Moving to four options classes with ValidateOnStart turned both bugs into start-up failures in the test environment, and the constructor of every service now listed exactly which settings it used.

🔍 What the interviewer is checking

Checks that the candidate turns configuration into typed, validated dependencies rather than string lookups.

Green flags

  • Shows AddOptions<T>().BindConfiguration() with validation and ValidateOnStart.
  • Explains how the binder maps keys, defaults and conversions.
  • Gives concrete reasons against injecting IConfiguration (hidden dependencies, no validation, testing).
  • Knows IConfigureOptions/PostConfigure for computed values.

Red flags

  • Reads IConfiguration["..."] throughout services.
  • Thinks a missing section throws by default.
  • Mutates options objects at run time.

📚 Learn in depth

1. What gets registered

AddOptions<T>() registers the open-generic options infrastructure once. Each piece has one job:

IOptions<T>          → UnnamedOptionsManager<T>   (singleton)  calls the factory once, caches forever
IOptionsSnapshot<T>  → OptionsManager<T>          (scoped)     calls the factory once per scope (request)
IOptionsMonitor<T>   → OptionsMonitor<T>          (singleton)  caches per name, rebuilds after change tokens fire
IOptionsFactory<T>   → OptionsFactory<T>          (transient)  builds an instance: new T, configure, post-configure, validate
IOptionsMonitorCache<T> → OptionsCache<T>         (singleton)  the per-name cache the monitor uses

The three interfaces you inject differ only in how long they keep what the factory built; the configuration, post-configuration and validation steps are identical. BindConfiguration adds an IConfigureOptions<T> that binds the section, plus an IOptionsChangeTokenSource<T> so the monitor knows when to rebuild.

2. How an options object is built

OptionsFactory<T>.Create(name) runs a fixed pipeline every time it builds an instance:

new T()                             (public parameterless constructor)
  │
  ├─► every IConfigureNamedOptions<T> / IConfigureOptions<T>  in registration order
  │     (BindConfiguration, Configure(o => ...), ConfigureOptions<X>)
  ├─► every IPostConfigureOptions<T>                            in registration order
  └─► every IValidateOptions<T>   ── any failure ─► OptionsValidationException

So a Configure registered later overrides an earlier one, and PostConfigure always runs last.

3. The binder

ConfigurationBinder.Bind uses reflection: for each public property with a setter (including init), it looks for a child key with the same name, ignoring case. Scalars are converted with the type's TypeConverter using the invariant culture, so "0.3" is a decimal on every server and "0,3" fails. Collections are filled from child sections; for arrays, items are appended to existing ones. BinderOptions.BindNonPublicProperties and ErrorOnUnknownConfiguration change the defaults.

4. The source generator

Setting <EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator> (automatic when PublishAot is on) makes the compiler intercept Bind, Get<T> and BindConfiguration calls and generate binding code, so trimming does not remove the properties the reflection binder would need.

5. Why IConfiguration in services hurts

Class needs IConfiguration      Class needs IOptions<PaymentOptions>
  → can read ANY key              → depends on exactly one section
  → string keys, no validation    → typed, validated at start-up
  → test: build config tree       → test: Options.Create(new PaymentOptions { ... })

Try it yourself

  1. Bind a section with a TimeSpan, a List<string> and a Dictionary<string,int>; print the result as JSON.
  2. Put "abc" into an int property and read the exception message.
  3. Add a typo key and turn on ErrorOnUnknownConfiguration; see the error.
  4. Register Configure<T> twice with different values and check which wins; add PostConfigure and check again.
  5. Unit test a service with Options.Create(new PaymentOptions { ... }) and no configuration at all.

💻 Code

Binding, validating and consuming a section, and testing the consumer without any configuration.

// PaymentOptions.cs
using System.ComponentModel.DataAnnotations;

namespace Shop.Payments;

public sealed class PaymentOptions
{
    public const string Section = "Payments";

    [Required, Url] public string BaseUrl { get; init; } = "";
    [Range(typeof(TimeSpan), "00:00:01", "00:01:00")] public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(10);
    [Range(0, 5)] public int Retries { get; init; } = 3;
    public List<string> Regions { get; init; } = [];
}
// Program.cs
using Shop.Payments;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOptions<PaymentOptions>()
    .BindConfiguration(PaymentOptions.Section, o => o.ErrorOnUnknownConfiguration = true) // typos fail loudly
    .ValidateDataAnnotations()
    .ValidateOnStart();                                 // bad config stops the app at start-up

// Typed client configured from options: the dependency is explicit
builder.Services.AddHttpClient<PaymentGateway>((sp, http) =>
{
    var o = sp.GetRequiredService<Microsoft.Extensions.Options.IOptions<PaymentOptions>>().Value;
    http.BaseAddress = new Uri(o.BaseUrl);
    http.Timeout = o.Timeout;
});

var app = builder.Build();
app.MapPost("/pay", (PaymentGateway gw, CancellationToken ct) => gw.PingAsync(ct));
app.Run();

public sealed class PaymentGateway(HttpClient http)
{
    public async Task<IResult> PingAsync(CancellationToken ct) =>
        (await http.GetAsync("health", ct)).IsSuccessStatusCode ? Results.Ok() : Results.StatusCode(502);
}
// Unit test: no configuration tree needed
var options = Microsoft.Extensions.Options.Options.Create(new PaymentOptions { BaseUrl = "https://test", Retries = 1 });

⚠ Common mistakes

  • Mistake: Injecting IConfiguration into services and reading keys with strings. Why it is wrong: Typos return null, dependencies are hidden and nothing is validated. Instead: Bind a section to an options class and inject IOptions<T>.
  • Mistake: Calling config.GetSection("X").Get<T>() inside a constructor. Why it is wrong: It rebinds with reflection on every resolve and bypasses validation and change tracking. Instead: Register with AddOptions<T>().BindConfiguration(...).
  • Mistake: Using a section name that doesn't match the JSON. Why it is wrong: The binder finds nothing and every property silently keeps its default. Instead: Keep the name in a const Section and validate required properties with ValidateOnStart.
  • Mistake: Writing numbers or dates in a local culture's format, such as "0,5" with a comma decimal separator or "18/11/2026". Why it is wrong: The binder always converts with CultureInfo.InvariantCulture, whatever the server's culture, so a comma decimal fails conversion (or is misread) and the bind throws InvalidOperationException. Instead: Store invariant formats in configuration: 0.5, ISO 8601 dates (2026-11-18), hh:mm:ss for TimeSpan.
  • Mistake: Making an options class immutable with only a parameterised constructor. Why it is wrong: OptionsFactory<T> creates the instance with new T(), so AddOptions<T>() requires a public parameterless constructor (the T : class registration has a new() expectation at run time), and the binder then sets properties. Instead: Keep a public parameterless constructor (the implicit one is fine) and use init properties with defaults; that gives read-only-after-binding semantics without breaking the factory.
  • Mistake: Reading options in Program.cs with builder.Configuration.Get<T>() and also registering them. Why it is wrong: You now have two sources of truth that can diverge after PostConfigure or validation. Instead: Resolve IOptions<T> from the provider when you need the value at start-up, or keep the read in one place.
  • Mistake: Mutating the options object at run time. Why it is wrong: IOptions<T>.Value is a shared singleton instance; every consumer sees the change, with no thread safety. Instead: Treat options as read-only; use init setters.

🏛 Senior insight: trade-offs

Options classes are part of the service's contract with operations, so I design them like an API: small, one per concern, with safe defaults and validation that explains what is wrong. The pattern also gives you a seam for testing that IConfiguration never did. Where I stop is wrapping options in further abstractions (ISettingsProvider around IOptions<T>): the framework already provides the abstraction, lifetimes and change tracking.

Option When it fits Cost When not to
AddOptions<T>().BindConfiguration Any structured setting used by services One class per section A single value read once in Program.cs
IConfigureOptions<T> Values derived from other services or secrets An extra class Plain binding
IConfiguration directly Composition root, library extension methods taking a section Magic strings Inside business services
Binding source generator Native AOT, trimming Build-time generation Nothing to lose: turn it on for AOT apps

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions where the bound values come from. Why: Checks they understand provider order behind the section being bound.
    How to answer

    ASP.NET Core configuration is a layered key-value store. IConfiguration merges an ordered list of providers into one flat, case-insensitive dictionary. WebApplication.CreateBuilder adds, in order: appsettings.json, appsettings.{Environment}.json, user secrets (only in Development), environment variables and command-line arguments. When two providers set the same key, the one added last wins, so an environment variable on the server overrides the JSON file you shipped.

    • Hierarchy is flattened with :, e.g. ConnectionStrings:Default.
    • Environment variables use __ instead, e.g. ConnectionStrings__Default, because : is not allowed in Linux variable names.

    The trade-off: layering lets one build artifact run everywhere, but a value can come from five places, so you need to know the order to find out which one won.

  2. When: Candidate mentions options lifetimes or injecting options into singletons. Why: Checks awareness of captive dependencies, e.g. a scoped IOptionsSnapshot captured by a singleton.
    How to answer

    A captive dependency is a service held by a consumer that lives longer than it should. Most often a scoped service (such as DbContext or a current-user service) is injected into a singleton, so it is created once and shared by every request. That leads to cross-user data leaks, "A second operation was started on this context instance", stale tracked entities and ObjectDisposedException.

    ValidateScopes throws when a scoped service is resolved from the root or from a singleton. ValidateOnBuild checks every registration when the provider is built. Both are on only in Development by default, so turn them on in tests too.

    The fix is either to make the consumer scoped, or to inject IServiceScopeFactory and create a scope per unit of work. A transient captured by a singleton is also captive, and validation won't catch it.

↩ Usually asked after

More in Configuration

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me