Advertisement
Advanced .NET, Configuration & Options

How would you write a custom configuration provider to load settings from an unsupported source, like a remote database?

Short answer

You implement IConfigurationSource (returning an IConfigurationProvider instance) and a corresponding ConfigurationProvider subclass overriding Load() to populate the provider's internal Data dictionary from your custom source, then register it via an extension method calling…

Save .NET mock interview
Advertisement
AModel answer
You implement IConfigurationSource (returning an IConfigurationProvider instance) and a corresponding ConfigurationProvider subclass overriding Load() to populate the provider's internal Data dictionary from your custom source, then register it via an extension method calling configurationBuilder.Add(new MyCustomSource()) -- this integrates seamlessly with the rest of the configuration system, including layering with other providers and (if you implement change detection) triggering hot-reload.
public class DatabaseConfigurationProvider : ConfigurationProvider {
    public override void Load() {
        using var connection = new SqlConnection(_connectionString);
        var settings = connection.Query("SELECT [Key], [Value] FROM AppSettings");
        foreach (var s in settings) Data[s.Key] = s.Value;
    }
}

public class DatabaseConfigurationSource : IConfigurationSource {
    public IConfigurationProvider Build(IConfigurationBuilder builder) => new DatabaseConfigurationProvider();
}

// Usage: builder.Configuration.Add(new DatabaseConfigurationSource());
Real-world example
A multi-tenant SaaS platform builds a custom configuration provider that loads tenant-specific feature flags from a database table at startup, integrating seamlessly alongside the standard appsettings.json and environment variable providers.
Likely follow-ups
  • How would you add live change detection (polling or push notifications) to this custom provider?
  • How does provider registration order affect precedence for a custom source?
Related topics