7.5 — The IConfiguration API¶
← Roadmap · Section: 7. Configuration and Options Prev: 7.4 Secret providers · Next: 7.6 The options pattern
Markers: ⭐ 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
IConfiguration is the merged, read-only view of every provider. You read values from it by
key path.
config["Key:Path"]returns a string or null. It never throws for a missing key.GetValue<T>()converts to a type and lets you supply a default.GetSection()never returns null — a missing section is an empty one, which is why typos fail silently.
⚠️ In application code you should mostly use IOptions<T> instead (7.6). IConfiguration is for Program.cs.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
IConfiguration |
an interface | The merged key/value store. Read-only. Injectable. |
IConfigurationSection |
an interface | A subtree, addressed by key prefix. Also an IConfiguration. |
IConfigurationRoot |
an interface | The top-level configuration. Adds Reload() and GetDebugView(). |
| Indexer | config["Key"] |
Returns string?. Null when absent. Never throws. |
GetValue<T> |
an extension method | Converts to T, with an optional default. |
GetSection |
a method | Returns a section. Never null — absent means empty. |
GetChildren |
a method | The immediate children of a section. |
Exists() |
an extension method | Whether a section actually has a value or children. |
GetConnectionString |
an extension method | Shorthand for ["ConnectionStrings:Name"]. |
Get<T> |
an extension method | Binds a whole section to an object. See 7.7. |
GetRequiredSection |
a method (.NET 7+) | Like GetSection but throws if absent. |
The concept¶
Everything is a string¶
Configuration is a flat dictionary of strings (7.1). Even this:
is stored as:
So reading is really two steps: look up a string, then convert it. The API gives you both.
⚠️ The silence problem¶
The single most important thing about this API is what it does when something is missing:
var value = config["Ordres:MaxItems"]; // typo — "Ordres"
// value is null. No exception. No warning.
var section = config.GetSection("Payments:Strpe"); // typo
// Returns an EMPTY section, not null. Reading from it gives you nulls.
Nothing tells you. A misspelled key produces a null, which becomes a default, which becomes wrong behaviour somewhere far away.
A picture: a filing cabinet that hands you an empty folder for any label you ask for. It never says "no such file" — you just get nothing and have to notice.
That silence is the argument for 7.6 and 7.8: bind to a typed class and validate it at startup, so a missing setting fails loudly at boot rather than quietly at runtime.
How it works¶
The simple version — reading values¶
// String, by key path. Null if absent.
string? name = config["Orders:QueueName"];
// Typed, with conversion
int maxItems = config.GetValue<int>("Orders:MaxItems");
// Typed, with a default when absent
int timeout = config.GetValue("Orders:TimeoutSeconds", 30);
// Connection strings — shorthand for ConnectionStrings:Default
string? cs = config.GetConnectionString("Default");
⚠️ GetValue<int> on a missing key returns default(T) — zero — not an error. A missing
MaxItems silently becomes 0, and your application processes nothing while looking healthy.
Always supply a default, or validate. The two-argument form makes the intent explicit:
⚠️ And a malformed value does throw, unlike a missing one:
// "Orders:MaxItems" = "abc"
config.GetValue<int>("Orders:MaxItems");
// InvalidOperationException: Failed to convert configuration value...
So missing is silent and invalid is loud — an inconsistency worth remembering.
Sections¶
IConfigurationSection orders = config.GetSection("Orders");
// A section is itself an IConfiguration, so keys are now relative
int max = orders.GetValue<int>("MaxItems");
string? queue = orders["QueueName"];
// Nested
IConfigurationSection stripe = config.GetSection("Payments:Stripe");
GetSection never returns null. Checking for null is pointless:
// ✗ Never true
if (config.GetSection("Payments") is null) { }
// ✓ This is the check you want
if (!config.GetSection("Payments").Exists())
throw new InvalidOperationException("The Payments section is missing.");
Since .NET 7 there is a stricter version:
Prefer GetRequiredSection for anything mandatory. It converts a silent failure into a clear
one, at the point you ask.
Enumerating¶
// Immediate children of a section
foreach (IConfigurationSection child in config.GetSection("Features").GetChildren())
{
Console.WriteLine($"{child.Key} = {child.Value}");
}
That is how you read a dictionary-shaped section whose keys you do not know in advance:
var features = config.GetSection("Features")
.GetChildren()
.ToDictionary(c => c.Key, c => bool.Parse(c.Value!));
Arrays¶
Arrays are indexed keys (7.1), so:
// Bind the whole thing
string[] origins = config.GetSection("AllowedOrigins").Get<string[]>() ?? [];
// Or read one
string? first = config["AllowedOrigins:0"];
// Or enumerate
var all = config.GetSection("AllowedOrigins").GetChildren().Select(c => c.Value!);
How it actually works — where to use it¶
⚠️ This is the part that matters for code review.
IConfiguration is injectable, so you can use it anywhere:
// ✗ Works, and is the wrong pattern
public class OrderService(IConfiguration config)
{
public void Process()
{
var max = config.GetValue<int>("Orders:MaxItems"); // stringly-typed
}
}
Three problems. The key is a magic string with no compile-time checking. There is no validation, so a missing value silently becomes zero. And the class's real dependency — a number — is hidden behind a general-purpose configuration object, which makes it awkward to test.
Bind to a typed options class instead:
// ✓ Typed, validated, and the dependency is explicit
public class OrderService(IOptions<OrderOptions> options)
{
private readonly OrderOptions _options = options.Value;
public void Process()
{
var max = _options.MaxItems; // a real property
}
}
The rule: IConfiguration belongs in Program.cs. Application services take IOptions<T>.
The deeper detail — debugging¶
When a value is not what you expect, this answers it immediately:
It prints every key, its value, and which provider supplied it:
Orders:
MaxItems=100 (JsonConfigurationProvider for 'appsettings.json')
ConnectionStrings:
Default=Server=prod;... (EnvironmentVariablesConfigurationProvider)
That last column is what you actually need — the usual cause of a surprising value is a provider you forgot about overriding it.
⚠️ Never leave GetDebugView in production code. It prints secrets. Gate it behind a
Development check, or use it only while diagnosing and remove it.
Code¶
Realistic use — all in Program.cs, none in services:
var builder = WebApplication.CreateBuilder(args);
// Required — fail at startup with a clear message
var connectionString = builder.Configuration.GetConnectionString("Default")
?? throw new InvalidOperationException(
"ConnectionStrings:Default is not configured. Set it via User Secrets " +
"locally or the ConnectionStrings__Default environment variable.");
builder.Services.AddDbContext<AppDbContext>(o => o.UseSqlServer(connectionString));
// Optional with a sensible default
var maxConcurrency = builder.Configuration.GetValue("Processing:MaxConcurrency", 4);
// Conditional wiring based on configuration
if (builder.Configuration.GetValue<bool>("Features:UseRedisCache"))
{
var redis = builder.Configuration.GetRequiredSection("Redis"); // throws if absent
builder.Services.AddStackExchangeRedisCache(o =>
o.Configuration = redis["ConnectionString"]);
}
else
{
builder.Services.AddDistributedMemoryCache();
}
// Everything else gets bound to typed options — services never see IConfiguration
builder.Services.Configure<OrderOptions>(builder.Configuration.GetSection("Orders"));
builder.Services.Configure<PaymentOptions>(builder.Configuration.GetSection("Payments"));
var app = builder.Build();
// Debugging aid — Development only, because it prints secrets
if (app.Environment.IsDevelopment())
{
app.Logger.LogDebug("Configuration:\n{Config}",
((IConfigurationRoot)builder.Configuration).GetDebugView());
}
Note the pattern: IConfiguration is used to wire things up, and every service receives typed
options. No service in this application injects IConfiguration.
Interview questions¶
Q: What happens when you read a configuration key that does not exist?
The indexer returns null, and GetValue<T> returns default(T) — so a missing integer silently
becomes zero rather than throwing. GetSection never returns null either; an absent section
comes back as an empty section, so a typo in a section name produces silence rather than an
error. That is the main weakness of the API: mistakes are quiet. A malformed value does throw,
though, so missing is silent and invalid is loud, which is a slightly awkward inconsistency.
Q: How do you check whether a section exists?
With Exists(), because comparing against null never works — GetSection always returns an
object. Since .NET 7 there is also GetRequiredSection, which throws immediately if the section
is absent, and I would prefer that for anything mandatory because it converts a silent failure
into a clear one at the point you ask rather than somewhere downstream.
Q: Should services inject IConfiguration?
Generally no. It works, but it means magic-string keys with no compile-time checking, no
validation so a missing value silently becomes a default, and the class's real dependency is
hidden behind a general-purpose object that is awkward to fake in tests. The better pattern is
to bind sections to typed options classes in Program.cs and have services take IOptions<T>,
so the dependency is a real typed object and can be validated at startup. IConfiguration is
for the composition root.
Q: How do you find out which provider supplied a value?
Cast the configuration to IConfigurationRoot and call GetDebugView, which prints every key,
its value, and the provider it came from. That is usually the fastest way to diagnose a
surprising setting, because the cause is almost always a provider later in the chain overriding
the one you were looking at. The important caveat is that it prints secrets, so it must never
run in production — gate it behind a Development check.
Traps ⚠️¶
- A missing key returns null or
default(T), silently. A missing int becomes zero. - A malformed value throws, unlike a missing one. Inconsistent, and worth remembering.
GetSectionnever returns null. Checking for null is dead code — useExists().- Injecting
IConfigurationinto services gives you magic strings and no validation. GetDebugViewprints secrets. Development only.- Key lookup is case-insensitive, which is convenient but means
orders:maxitemsalso works — so casing inconsistencies hide. - Arrays are indexed keys, so partial overrides leave the original tail elements (7.2).
GetValue<T>cannot bind complex objects. UseGet<T>or the options pattern.
Related¶
- 7.1 The configuration system — how keys are built
- 7.6 The options pattern — what services should use instead
- 7.7 Binding to POCOs —
Get<T>andBind - 7.8 Options validation — failing fast on missing values
- 7.2 appsettings.json — the array trap
- 6.9 Injection styles — why hidden dependencies hurt