Advertisement
Advanced ASP.NET Core, Configuration & Options Pattern

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

Short answer

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 configurationBuilder.Add(new…

Save ASP.NET Core mock interview
Advertisement
AModel answer
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 configurationBuilder.Add(new MyCustomSource()) -- integrating 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();
}
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