Advertisement
Intermediate .NET, Generic Host

How do you configure the Generic Host to read configuration from a custom file format or remote source before the rest of the application starts?

Short answer

Configuration sources are added to builder.Configuration before calling Build(), and since configuration is fully assembled before any services are constructed, you can add custom IConfigurationSource implementations (or built-in ones like Azure App Configuration or Key Vault…

Save .NET mock interview
Advertisement
AModel answer
Configuration sources are added to builder.Configuration before calling Build(), and since configuration is fully assembled before any services are constructed, you can add custom IConfigurationSource implementations (or built-in ones like Azure App Configuration or Key Vault providers) at this stage, and even use an already-partially-built configuration to conditionally add further sources (like only adding a remote source if a certain flag is present in local configuration).
var builder = Host.CreateApplicationBuilder(args);

// Add a custom or remote source before Build()
builder.Configuration.AddAzureAppConfiguration(builder.Configuration["AppConfig:ConnectionString"]);

// All services registered afterward see the fully merged configuration
builder.Services.Configure<FeatureSettings>(builder.Configuration.GetSection("Features"));
Real-world example
An application conditionally adds an Azure App Configuration source only when a connection string for it is present in local appsettings.json, letting the same codebase run correctly both with and without the centralized configuration service configured.
Likely follow-ups
  • What's the risk of a remote configuration source being unavailable at startup?
  • How does provider registration order affect precedence when adding sources this way?
Related topics