ASP.NET Core Interview Question #47

How can custom configuration be added in Program.cs?

Application Structure & Configuration Junior Beginner

Quick Interview Answer

Custom configuration sources can be added through builder.Configuration before the application is built. Examples include an additional JSON file, an in-memory dictionary, environment variables with a prefix, or a custom configuration provider.

Detailed Explanation

Custom configuration sources can be added through builder.Configuration before the application is built. Examples include an additional JSON file, an in-memory dictionary, environment variables with a prefix, or a custom configuration provider.

This is useful when an application has settings stored outside the default appsettings files. The added provider becomes part of the same IConfiguration abstraction used by the rest of the application.

Provider order should be deliberate because later sources can override existing keys.

Code Example

var initialSettings = new Dictionary<string, string?>
{
    ["Features:EnableReports"] = "true"
};

builder.Configuration
    .AddInMemoryCollection(initialSettings)
    .AddJsonFile("features.json", optional: true, reloadOnChange: true);