7.10 — Writing a Custom Configuration Provider¶
← Roadmap · Section: 7. Configuration and Options Prev: 7.9 Reload on change · Next: 7.11 Feature flags
Markers: 🧠 💻 · Confidence: 🔴 · Last reviewed: —
TL;DR¶
A custom configuration provider lets you pull settings from a source ASP.NET Core does not support out of the box — a database table, an internal config service, a proprietary format.
- Three pieces: a source (the recipe), a provider (does the loading), and an extension method (the friendly API).
- Inherit
ConfigurationProviderand overrideLoad(), filling the inheritedDatadictionary. - ⚠️ Ask whether you need one first. A database provider in particular has a startup-ordering problem worth understanding.
Definitions¶
| Term | What it is | What it means |
|---|---|---|
IConfigurationSource |
an interface | A factory. Its Build method creates the provider. |
IConfigurationProvider |
an interface | Loads key/value pairs and answers lookups. |
ConfigurationProvider |
an abstract class | Base implementation. Override Load() and fill Data. |
Data |
a protected property | IDictionary<string, string?>. Where your provider puts its values. |
Load() |
a method | Called at startup, and again on reload. Populates Data. |
OnReload() |
a method | Signals that values changed, so IOptionsMonitor fires. |
ConfigurationKeyDelimiter |
a constant | ":". Use it to build nested keys. |
AddXxx extension |
a method | The friendly registration API, on IConfigurationBuilder. |
| Startup ordering | a constraint | Providers load before DI exists, so a provider cannot inject services. |
The concept¶
When you would need one¶
The built-in providers cover JSON, XML, INI, environment variables, command line, User Secrets, Key Vault and Secrets Manager (7.1). That is most cases.
You write your own when configuration lives somewhere else:
- A database table, so non-developers can change settings through an admin screen
- An internal configuration service your company already runs
- A proprietary or legacy format — a YAML file, or something bespoke
- A remote store with no existing provider
A picture: a translator for a language the library does not speak. The library already reads English, French and German. If your settings are written in something else, you supply someone who can read it and dictate the contents in a form the library understands.
⚠️ Ask whether you need one¶
Before writing one, three questions:
Could environment variables do it? They cover most deployment-specific values and need no code (7.3).
Is this really configuration, or is it data? Settings that change per user, per tenant or
during normal operation are application data, not configuration. They belong in a repository
you query, not in IConfiguration — which is loaded once at startup and shared across every
request.
Do you want feature flags? There is a purpose-built system for runtime toggles (7.11).
The database provider in particular is worth thinking twice about, for the reason below.
How it works¶
The simple version — the three pieces¶
1. The source — a factory the builder holds:
public class DatabaseConfigurationSource : IConfigurationSource
{
public required string ConnectionString { get; init; }
public TimeSpan? ReloadInterval { get; init; }
public IConfigurationProvider Build(IConfigurationBuilder builder)
=> new DatabaseConfigurationProvider(this);
}
2. The provider — does the work:
public class DatabaseConfigurationProvider : ConfigurationProvider
{
private readonly DatabaseConfigurationSource _source;
public DatabaseConfigurationProvider(DatabaseConfigurationSource source)
=> _source = source;
// Called once at startup, and again whenever you decide to reload
public override void Load()
{
var data = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
using var connection = new SqlConnection(_source.ConnectionString);
connection.Open();
using var command = new SqlCommand("SELECT [Key], [Value] FROM AppSettings", connection);
using var reader = command.ExecuteReader();
while (reader.Read())
data[reader.GetString(0)] = reader.IsDBNull(1) ? null : reader.GetString(1);
Data = data; // the inherited dictionary the framework reads from
}
}
Three details in that:
StringComparer.OrdinalIgnoreCase — configuration lookup is case-insensitive
(7.5), so your dictionary must be too, or orders:maxitems will
not find Orders:MaxItems.
Load() is synchronous. There is no async version, because it runs during
builder.Build() before the host is running. Blocking here is expected.
Nested keys use colons, so a row with the key Orders:MaxItems becomes a nested setting
automatically.
3. The extension method — so it reads like the built-in ones (1.14):
public static class DatabaseConfigurationExtensions
{
public static IConfigurationBuilder AddDatabase(
this IConfigurationBuilder builder,
string connectionString,
TimeSpan? reloadInterval = null)
{
return builder.Add(new DatabaseConfigurationSource
{
ConnectionString = connectionString,
ReloadInterval = reloadInterval
});
}
}
// Program.cs — indistinguishable from a built-in provider
builder.Configuration.AddDatabase(
builder.Configuration.GetConnectionString("Config")!,
reloadInterval: TimeSpan.FromMinutes(5));
⚠️ The startup-ordering problem¶
This is the interesting constraint, and the reason a database provider needs care.
Configuration providers run before dependency injection exists. builder.Build() has not been
called, so there is no container, no DbContext, no logger.
So a database provider cannot:
It must open its own connection with a raw SqlConnection, using a connection string that came
from an earlier provider — which is why the example above reads it from
builder.Configuration before adding itself.
That creates a bootstrap chain: the database connection string must come from somewhere that
loads first, usually an environment variable or appsettings.json.
⚠️ And there is a worse failure mode. If the database is unreachable at startup, Load()
throws and the application does not start. A configuration source that is also a runtime
dependency turns a transient database outage into a failure to boot.
Handle it deliberately:
public override void Load()
{
try
{
// ... load from the database ...
}
catch (SqlException) when (_source.Optional)
{
Data = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
// Continue with no values rather than refusing to start.
// The app then relies on defaults from earlier providers.
}
}
That mirrors optional: true on AddJsonFile, and it is the right shape — but note the
trade-off: starting with missing configuration may be worse than not starting. Options validation
decides which (7.8).
How it actually works — supporting reload¶
To make IOptionsMonitor see changes (7.6), call OnReload() after
refreshing Data:
public class DatabaseConfigurationProvider : ConfigurationProvider, IDisposable
{
private readonly DatabaseConfigurationSource _source;
private readonly Timer? _timer;
public DatabaseConfigurationProvider(DatabaseConfigurationSource source)
{
_source = source;
if (source.ReloadInterval is { } interval)
{
_timer = new Timer(_ => ReloadFromDatabase(), null, interval, interval);
}
}
private void ReloadFromDatabase()
{
try
{
var previous = Data;
Load();
// Only notify if something actually changed — OnReload is not free,
// and every IOptionsMonitor subscriber runs its callback
if (HasChanged(previous, Data))
OnReload();
}
catch
{
// A failed refresh must NOT crash the app — keep the previous values
}
}
public void Dispose() => _timer?.Dispose();
}
Three deliberate choices:
Only call OnReload when values changed. Every subscriber's callback fires otherwise, and
those callbacks can be expensive (7.9).
Swallow refresh failures. A transient database blip should not take down a running application — keep serving the last known good values.
Dispose the timer, or it keeps the provider alive for the process lifetime.
The deeper detail — a simpler alternative¶
⚠️ For database-backed settings, a repository is often the better design:
Compared with a configuration provider, that gives you:
- Async access, rather than blocking
Load() - Per-request or per-tenant values, which
IConfigurationcannot express - Normal DI, so it can use
DbContext, caching and logging - No startup dependency — a database outage does not prevent booting
- Ordinary error handling, rather than a provider that must not throw
Use a configuration provider when the values genuinely are application-wide configuration read at startup. Use a repository when they are data that changes during normal operation.
That distinction — configuration versus data — is the useful part of this topic, more than the mechanics.
Code¶
A complete, minimal provider for a simpler case — a YAML file, where the ordering problem does not arise:
public class YamlConfigurationSource : FileConfigurationSource
{
public override IConfigurationProvider Build(IConfigurationBuilder builder)
{
EnsureDefaults(builder); // sets the file provider and path
return new YamlConfigurationProvider(this);
}
}
public class YamlConfigurationProvider(YamlConfigurationSource source)
: FileConfigurationProvider(source)
{
// FileConfigurationProvider gives us file watching and reloadOnChange for free
public override void Load(Stream stream)
{
var deserializer = new DeserializerBuilder().Build();
var yaml = deserializer.Deserialize<Dictionary<string, object>>(new StreamReader(stream));
var data = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
Flatten(yaml, prefix: "", data);
Data = data;
}
private static void Flatten(
Dictionary<string, object> source, string prefix, Dictionary<string, string?> target)
{
foreach (var (key, value) in source)
{
var path = string.IsNullOrEmpty(prefix)
? key
: $"{prefix}{ConfigurationPath.KeyDelimiter}{key}";
switch (value)
{
case Dictionary<string, object> nested:
Flatten(nested, path, target); // recurse
break;
case IList<object> list:
for (var i = 0; i < list.Count; i++) // arrays → indexed keys
target[$"{path}{ConfigurationPath.KeyDelimiter}{i}"] = list[i]?.ToString();
break;
default:
target[path] = value?.ToString();
break;
}
}
}
}
public static class YamlConfigurationExtensions
{
public static IConfigurationBuilder AddYamlFile(
this IConfigurationBuilder builder, string path, bool optional = false,
bool reloadOnChange = false)
{
return builder.Add(new YamlConfigurationSource
{
Path = path,
Optional = optional,
ReloadOnChange = reloadOnChange
});
}
}
Inheriting FileConfigurationSource and FileConfigurationProvider is the shortcut worth
knowing. They handle file resolution, the optional flag, and the file watcher for
reloadOnChange — so you only implement the parsing.
Note the flattening logic: nested maps become colon-separated keys and lists become indexed keys, matching how the JSON provider behaves (7.1). Getting that consistent is what makes your provider behave like the built-in ones.
Interview questions¶
Q: How do you write a custom configuration provider?
Three pieces. An IConfigurationSource, which is a factory holding the settings and building the
provider. A provider inheriting ConfigurationProvider, overriding Load() to populate the
inherited Data dictionary with key/value pairs. And an extension method on
IConfigurationBuilder so it registers like the built-in ones. For a file-based format you
inherit FileConfigurationSource and FileConfigurationProvider instead, which give you file
resolution and the reload watcher for free so you only write the parsing.
Q: What constraint does a custom provider have that other components do not?
It runs before dependency injection exists. Providers load during builder.Build(), so there is
no container, no DbContext and no logger to inject. A database-backed provider has to open its
own raw connection using a connection string that came from an earlier provider, which creates a
bootstrap chain. It also means a failure in Load() prevents the application starting entirely —
so a configuration source that is also a runtime dependency turns a transient database outage
into a failure to boot, which needs handling deliberately.
Q: How do you support reloading in a custom provider?
Call the inherited OnReload() after refreshing Data, which raises the change token that
IOptionsMonitor and IOptionsSnapshot listen to. For a polling source you would use a timer to
re-run Load on an interval. Two things worth doing: only call OnReload when values actually
changed, because every subscriber's callback fires and those can be expensive; and swallow
failures during a refresh, since a transient outage should leave the last known good values in
place rather than taking down a running application.
Q: When would you use a configuration provider versus a repository for database-backed settings?
The question is whether it is configuration or data. Configuration is application-wide, read at startup, and the same for every request — a provider suits that. If the values change during normal operation, or vary per user or per tenant, they are data and belong in a repository you query. A repository is also better practically: it can be async, it uses normal DI so it can have caching and logging, a database outage does not prevent startup, and errors are handled normally rather than inside a provider that must not throw.
Traps ⚠️¶
- Providers run before DI exists. You cannot inject services into one.
- A throwing
Load()prevents the application starting. Support anoptionalflag. Datamust use a case-insensitive comparer, or lookups fail inconsistently.Load()is synchronous. There is no async version — it runs before the host starts.- Forgetting
OnReload()meansIOptionsMonitornever sees your changes. - Calling
OnReload()unconditionally runs every subscriber's callback even when nothing changed. - Nested keys need
:and arrays need indexed keys, or your provider behaves differently from the built-in ones. - A polling timer must be disposed, or it keeps the provider alive for the process lifetime.
- Per-request or per-tenant values are data, not configuration.
IConfigurationis loaded once and shared.
Related¶
- 7.1 The configuration system — how providers combine
- 7.5 The IConfiguration API — case-insensitive lookup
- 7.9 Reload on change — what
OnReloadtriggers - 7.11 Feature flags — the purpose-built alternative for toggles
- 7.4 Secret providers — a provider you get for free
- 1.14 Extension methods — the registration API
- 4.3 Program.cs — where providers are added