skip to content

In ASP.NET Core, how do you build a custom configuration provider that loads feature switches from a database, and where does builder.Configuration.Add place it?

level: seniorimportance: nice to knowfreq 28%

answer

  1. a source builds a provider
  2. derive from ConfigurationProvider
  3. override Load, fill Data
  4. OnReload after a refresh
  5. added last means highest precedence

basics

~20 s

Write an IConfigurationSource whose Build returns a class derived from ConfigurationProvider, override Load to fill Data with colon keys, and call OnReload after a refresh. Adding it after CreateBuilder appends it last, above environment variables and arguments.

solid answer

~40 s

A custom source has two parts: an `IConfigurationSource` whose `Build(IConfigurationBuilder)` returns the provider, and a provider derived from `ConfigurationProvider` that overrides `Load()` and fills the protected `Data` dictionary with keys such as `Features:VideoMeetAndGreet`. Load runs while the host is still being built, so it cannot resolve a `DbContext` from DI; open a connection with the connection string already in configuration. To refresh, reload on a timer and call `OnReload()` so the reload token fires. Registered with `builder.Configuration.Add(source)` after `CreateBuilder`, it lands at the end of the chain and overrides environment variables and the command line; insert it into `builder.Configuration.Sources` to sit lower. `AddInMemoryCollection` is the built-in provider for code-supplied pairs, handy for defaults and tests, with the same position rule.

code

csharp · 13 lines
csharp
using Microsoft.Extensions.Configuration.Memory;

var builder = WebApplication.CreateBuilder(args);

// defaults below the files: insert at the front of the chain
builder.Configuration.Sources.Insert(0, new MemoryConfigurationSource
{
    InitialData = new Dictionary<string, string?>
    {
        ["Features:OnlineApplications"] = "true",
        ["Features:VideoMeetAndGreet"] = "false",
    }
});

go deeper

for a junior

Know that AddInMemoryCollection supplies key-value pairs from code and that later sources override earlier ones.

for a middle

Describe the source and provider pair, filling Data with colon keys in Load, and registering it with builder.Configuration.Add.

for a senior

Handle the constraints: no DI during Load, synchronous I/O, startup failures, refresh with OnReload, and a deliberate place in the precedence chain.

for a principal

Weigh a home-grown database provider against an external configuration service and decide who may change live switches and how changes are audited.

## The two types The configuration system builds providers from **sources**: - `IConfigurationSource` has one method, `Build(IConfigurationBuilder builder)`, which returns an `IConfigurationProvider`. It holds the settings needed to create the provider, such as a connection string. - `ConfigurationProvider` is the abstract base class most providers derive from. It owns a protected `Data` dictionary (case-insensitive), implements `TryGet`, `Set` and `GetChildKeys`, and exposes `Load()` to override and `OnReload()` to call after new data arrives. Keys must use the configuration path format, with `:` between segments, so the rest of the app reads them like any JSON value. ```csharp public sealed class FeatureSwitchSource(string connectionString) : IConfigurationSource { public IConfigurationProvider Build(IConfigurationBuilder builder) => new FeatureSwitchProvider(connectionString); } public sealed class FeatureSwitchProvider(string cs) : ConfigurationProvider { public override void Load() { var data = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase); using var conn = new NpgsqlConnection(cs); conn.Open(); using var cmd = new NpgsqlCommand("select name, enabled from feature_switches", conn); using var reader = cmd.ExecuteReader(); while (reader.Read()) data[$"Features:{reader.GetString(0)}"] = reader.GetBoolean(1).ToString(); Data = data; } } ``` ## Constraints while loading 1. **No DI yet.** Providers load while `WebApplicationBuilder` is being built, before `builder.Build()` creates the service provider, so `Load` cannot ask for a `DbContext` or any registered service. Use plain ADO.NET or a client library directly. 2. **Load is synchronous.** The configuration system calls `Load()` with no async variant; keep the query small. 3. **Failures surface at startup.** An exception in `Load` aborts the build. Decide whether a dead database should stop the app or whether the provider should catch, log to the console and leave `Data` empty so lower sources answer. ## Registering it and its precedence ```csharp var builder = WebApplication.CreateBuilder(args); var cs = builder.Configuration.GetConnectionString("Adoptions")!; builder.Configuration.Add(new FeatureSwitchSource(cs)); ``` `ConfigurationManager` builds and loads the provider as soon as it is added, so values are readable on the next line. Position follows the usual rule, **last added wins**: | Registration | Effective precedence | |---|---| | `builder.Configuration.Add(source)` after `CreateBuilder` | Above everything, including environment variables and arguments | | `builder.Configuration.Sources.Insert(index, source)` | Wherever you insert it; changing the list rebuilds all providers | | Add, then call `AddEnvironmentVariables()` and `AddCommandLine(args)` again | Database values sit below variables and arguments again | Putting database switches on top means an operator can no longer override one with an environment variable in an emergency; many teams re-add the variables provider afterwards for exactly that reason. ## Refreshing while running A provider that should pick up database changes needs its own trigger: a timer that calls `Load()` and then `OnReload()`, or a notification from the database. `OnReload()` fires the provider's change token, the root's reload token follows, and every `IConfiguration` read sees the new switch. ## The in-memory provider `AddInMemoryCollection(IEnumerable<KeyValuePair<string, string?>>)` registers a `MemoryConfigurationSource`. It is a ready-made provider for values supplied in code: - Defaults that a later source may override, when added before the files. - Overrides in integration tests, where test hosts add a collection so the test controls a key. - Values computed at startup, such as a generated instance id. The same precedence rule applies: added after `CreateBuilder`, it overrides every default source. ## Choosing a mechanism | Need | Fits best | |---|---| | Fixed defaults known at compile time | `AddInMemoryCollection`, inserted low | | A test that must force one value | An in-memory collection added last in the test host | | Values an operator edits on the server | A JSON file with `reloadOnChange` | | Values kept in a database or remote store | A custom `IConfigurationSource` with its own refresh | A custom provider is the heaviest option: it adds a startup dependency on the database and code you must test and maintain. Reach for it when the values truly live elsewhere, not to avoid editing a file. ## Interview checklist - Source builds provider; provider overrides `Load` and fills `Data` with colon keys. - No DI inside `Load`; synchronous; exceptions stop startup. - `OnReload()` after a refresh. - Last added wins, so decide where the provider belongs.

  • Why can't the custom provider's Load method inject the app's DbContext?
    Configuration is built before `builder.Build()` creates the service provider, and other registrations may depend on the very values the provider loads. `Load` runs with no container available, so it must open its own connection from a connection string already present in configuration.
  • How would you let an operator override a database feature switch with an environment variable?
    Put the database source below the variables provider: either insert it into `builder.Configuration.Sources` before the environment-variables source, or call `builder.Configuration.AddEnvironmentVariables()` again after adding it, so a variable such as `Features__VideoMeetAndGreet` is found first.

  • A custom provider can resolve its DbContext from builder.Services inside Load.
  • A provider added after CreateBuilder sits below environment variables by default.
  • Changing Data in a refresh is enough; readers are notified without calling OnReload.
  • AddInMemoryCollection always has the lowest precedence because it lives in memory.
  • Provider keys use dots, like Features.VideoMeetAndGreet, to form sections.