Skip to content

7.7 — Binding Configuration to POCOs

← Roadmap · Section: 7. Configuration and Options Prev: 7.6 The options pattern · Next: 7.8 Options validation

Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —


TL;DR

Binding is populating a plain C# class from a configuration section by matching property names to keys.

  • Three ways: Configure<T> (registers it in DI), Get<T> (returns a new object), Bind (fills an existing one).
  • The class needs a parameterless constructor and settable properties, or binding silently produces defaults.
  • ⚠️ Unmatched keys are ignored and unmatched properties keep their defaults. Nothing warns you about a typo.

Definitions

Term What it is What it means
Binding a process Populating an object's properties from configuration keys by name.
POCO an acronym Plain Old CLR Object. A class with no base class, attributes or framework dependency.
Configure<T> a method Binds a section to T and registers IOptions<T> and friends in DI.
Get<T> an extension method Binds a section to a new T and returns it. Used in Program.cs.
Bind an extension method Populates an existing object.
BinderOptions a class Binding settings — ErrorOnUnknownConfiguration, BindNonPublicProperties.
ErrorOnUnknownConfiguration a binder option Throw if a configuration key has no matching property. Off by default.
Case-insensitive matching binder behaviour maxitems binds to MaxItems.
Configuration binding source generator a build feature (.NET 8+) Generates binding code at compile time. Needed for Native AOT.
required a C# keyword ⚠️ Not enforced by the binder. See traps.

The concept

What binding does

Given this configuration:

{
  "Orders": {
    "MaxItems": 100,
    "AutoApproveUnder": 50.00,
    "QueueName": "orders-main",
    "EnableNotifications": true
  }
}

and this class:

public class OrderOptions
{
    public int MaxItems { get; set; } = 50;
    public decimal AutoApproveUnder { get; set; }
    public string QueueName { get; set; } = "default";
    public bool EnableNotifications { get; set; }
}

binding matches property names to keys, converts the strings to the right types, and sets each property.

builder.Services.Configure<OrderOptions>(builder.Configuration.GetSection("Orders"));

Matching is case-insensitive, so maxitems, MaxItems and MAXITEMS all bind to MaxItems.

A picture: a form and a filing system. Binding is a clerk reading the filing system and filling in the form, field by field, by matching labels. If a label on the form has no matching file, the clerk leaves the field as it was — and says nothing.

⚠️ The silence problem

That last part is the thing to internalise:

A configuration key with no matching property is ignored.

{ "Orders": { "MaxItem": 100 } }      // typo: "MaxItem", not "MaxItems"

No error. The key is simply unused.

A property with no matching key keeps its default.

public int MaxItems { get; set; } = 50;    // stays 50 — you get the default, not an error

So a typo in either direction produces an application that runs with the wrong values and tells you nothing. That is the argument for 7.8 — validation is what turns this silence into a startup failure.


How it works

The simple version — the three methods

// 1. Configure<T> — bind AND register in DI. The normal choice.
builder.Services.Configure<OrderOptions>(builder.Configuration.GetSection("Orders"));
// Services then inject IOptions<OrderOptions>

// 2. Get<T> — bind to a new object, right now. For Program.cs.
var orderOptions = builder.Configuration.GetSection("Orders").Get<OrderOptions>();

// 3. Bind — populate an object you already have
var options = new OrderOptions();
builder.Configuration.GetSection("Orders").Bind(options);

Use Configure<T> for anything a service needs. Use Get<T> when you need a value during startup wiring:

// Needed while building the pipeline, before DI is available
var cacheOptions = builder.Configuration.GetSection("Cache").Get<CacheOptions>()
    ?? new CacheOptions();

if (cacheOptions.UseRedis)
    builder.Services.AddStackExchangeRedisCache(o => o.Configuration = cacheOptions.ConnectionString);

⚠️ Get<T> returns null if the section does not exist, so the null-coalescing fallback there is not optional.

What the class must look like

public class OrderOptions
{
    // ✓ Public settable property — binds
    public int MaxItems { get; set; }

    // ✓ Default used if the key is absent
    public string QueueName { get; set; } = "default";

    // ✗ Get-only — the binder cannot set it
    public int Computed => MaxItems * 2;

    // ✗ Private setter — not bound by default
    public string Secret { get; private set; } = "";

    // ✗ Field, not a property — ignored
    public int notAProperty;
}

Requirements: a public parameterless constructor, and public settable properties.

⚠️ init setters do work — the binder can set them during construction. But required does not:

public class OrderOptions
{
    public required string QueueName { get; init; }    // ⚠️ NOT enforced by binding
}

required is checked by the compiler at the call site (1.6). The binder constructs the object through reflection, bypassing that check entirely — so a missing key leaves it null despite the keyword promising otherwise.

Use [Required] from DataAnnotations plus validation instead (7.8).

⚠️ Records with positional parameters do not bind well either, because there is no parameterless constructor:

// ✗ Does not bind
public record OrderOptions(int MaxItems, string QueueName);

// ✓ Binds — a record with settable properties
public record OrderOptions
{
    public int MaxItems { get; set; }
    public string QueueName { get; set; } = "";
}

.NET 8 improved constructor binding, but a plain class with settable properties remains the reliable choice for options.

How it actually works — nested objects and collections

Binding is recursive:

{
  "Payments": {
    "TimeoutSeconds": 30,
    "Stripe": {
      "BaseUrl": "https://api.stripe.com",
      "WebhookSecret": "whsec_..."
    },
    "AllowedCurrencies": [ "GBP", "USD", "EUR" ],
    "Limits": {
      "GBP": 10000,
      "USD": 12000
    }
  }
}
public class PaymentOptions
{
    public int TimeoutSeconds { get; set; } = 30;
    public StripeOptions Stripe { get; set; } = new();              // nested object
    public List<string> AllowedCurrencies { get; set; } = [];       // array → list
    public Dictionary<string, decimal> Limits { get; set; } = [];   // section → dictionary
}

public class StripeOptions
{
    public string BaseUrl { get; set; } = "";
    public string WebhookSecret { get; set; } = "";
}

Three things bind here that people do not expect:

Nested classes bind automatically, as long as the property is initialised (= new()) or has a settable type the binder can construct.

Arrays bind to List<T> or T[] — the indexed keys become elements.

A section binds to Dictionary<string, T>, with the child keys becoming dictionary keys. That is genuinely useful for configuration that is a lookup rather than a fixed shape.

⚠️ Collections are added to, not replaced. If the property is initialised with items, the bound values are appended. Start collections empty.

Catching typos with ErrorOnUnknownConfiguration

The binder can be told to complain about keys it does not recognise:

builder.Services.Configure<OrderOptions>(
    builder.Configuration.GetSection("Orders"),
    binderOptions => binderOptions.ErrorOnUnknownConfiguration = true);

Now a key with no matching property throws at binding time, which catches the MaxItem typo.

⚠️ It only catches one direction. A property with no matching key still silently keeps its default — that needs validation (7.8).

⚠️ And it is strict. Any extra key in that section throws, including ones deliberately read elsewhere, so it works best on sections owned entirely by one options class.

The deeper detail — the source generator

Binding uses reflection by default, which means it does not survive trimming and does not work with Native AOT (3.2).

.NET 8 added a configuration binding source generator that produces the binding code at compile time:

<PropertyGroup>
  <EnableConfigurationBindingGenerator>true</EnableConfigurationBindingGenerator>
</PropertyGroup>

No code changes — the same Configure<T> calls are intercepted and replaced with generated code. You get AOT compatibility and slightly faster startup.

This is part of the broader move from runtime reflection to compile-time generation across .NET (1.23).


Code

A realistic options class and its registration:

public class PaymentOptions
{
    public const string SectionName = "Payments";     // avoids a magic string at the call site

    public string BaseUrl { get; set; } = "";
    public string ApiKey { get; set; } = "";
    public int TimeoutSeconds { get; set; } = 30;
    public int MaxRetries { get; set; } = 3;

    public List<string> AllowedCurrencies { get; set; } = [];
    public Dictionary<string, decimal> LimitsByCurrency { get; set; } = [];

    public StripeOptions Stripe { get; set; } = new();
}

public class StripeOptions
{
    public string WebhookSecret { get; set; } = "";
    public bool VerifySignatures { get; set; } = true;
}
// Program.cs
builder.Services
    .AddOptions<PaymentOptions>()
    .Bind(builder.Configuration.GetSection(PaymentOptions.SectionName))
    .ValidateDataAnnotations()
    .ValidateOnStart();                  // see 7.8

That SectionName constant is a small habit worth having. It keeps the string in one place, so renaming the section is one edit rather than a search-and-hope.

// The service — a plain typed dependency
public class PaymentService(IOptions<PaymentOptions> options, IHttpClientFactory factory)
{
    private readonly PaymentOptions _options = options.Value;

    public async Task<Receipt> ChargeAsync(decimal amount, string currency, CancellationToken ct)
    {
        if (!_options.AllowedCurrencies.Contains(currency))
            throw new NotSupportedException($"Currency {currency} is not enabled.");

        if (_options.LimitsByCurrency.TryGetValue(currency, out var limit) && amount > limit)
            throw new InvalidOperationException($"Amount exceeds the {currency} limit of {limit}.");

        // ...
    }
}

No configuration keys appear in the service at all. It receives a typed object, which is the whole point.


Interview questions

Q: How does configuration binding work?

It matches configuration keys to property names on a plain class, case-insensitively, converts the string values to the property types, and sets them. You either use Configure<T>, which binds a section and registers the options interfaces in DI, or Get<T> and Bind when you need the values during startup wiring. The class needs a public parameterless constructor and public settable properties — get-only and computed properties are skipped, as are fields. Binding is recursive, so nested objects, arrays and dictionaries all work.

Q: What happens if a key does not match any property, or vice versa?

Both are silently ignored by default. An unmatched configuration key is simply unused, and an unmatched property keeps whatever default the class gave it. So a typo in either direction produces an application running with the wrong values and no indication anything is wrong. You can set ErrorOnUnknownConfiguration to throw on unrecognised keys, but that only covers one direction — a property that never got a value still needs validation to be caught.

Q: Does required work on an options class?

No, and that is a genuine trap because it looks like it should. required is enforced by the compiler at the call site, but the binder constructs the object through reflection and sets properties afterwards, bypassing that check entirely. So a missing configuration key leaves the property null despite the keyword. The right tool is a [Required] DataAnnotations attribute combined with ValidateDataAnnotations and ValidateOnStart, which fails the application at startup rather than at first use.

Q: What is the configuration binding source generator?

A .NET 8 feature that generates the binding code at compile time instead of using reflection at runtime. You enable it with a property in the project file and your code does not change — the existing Configure<T> calls are intercepted and replaced. The reason it matters is that reflection-based binding does not survive trimming and does not work under Native AOT, since the trimmer removes the properties it cannot see being used. It is part of the same shift towards source generators that has happened for JSON serialization and logging.


Traps ⚠️

  • Typos are silent in both directions. An unmatched key is ignored; an unmatched property keeps its default.
  • required is not enforced by the binder. Use [Required] plus validation.
  • Positional records do not bind — no parameterless constructor.
  • Get-only and computed properties are skipped, as are public fields.
  • Collections are appended to, not replaced. Initialise them empty.
  • Get<T> returns null when the section is absent.
  • Reflection-based binding breaks under trimming and AOT. Enable the source generator.
  • ErrorOnUnknownConfiguration is strict — any extra key in the section throws.


Sources