liveBook · Manning

IConfiguration

As explained in ASP.NET Core in Action, 3e

IConfiguration is the .NET abstraction for reading aggregated application configuration values from key-value configuration sources.

IConfiguration is the .NET abstraction for reading the combined key-value settings supplied by configuration providers such as JSON files, environment variables, and command-line arguments. section 10.2

ASP.NET Core commonly exposes it through dependency injection, so endpoint handlers and application classes can read settings without knowing which provider supplied them. Use the indexer for keys such as Configuration["MapSettings:DefaultZoomLevel"]. section 10.2.1 section 10.5

Keep these configuration behaviors in mind:

  • Nested settings use colon-separated keys, such as MapSettings:DefaultLocation:Latitude. section 10.2.1
  • Later providers override values from earlier providers while preserving keys that exist only in earlier sources. section 10.5
  • WebApplicationBuilder configures common providers automatically, while ConfigurationManager can accept additional providers or replace the defaults. section 10.2.1 section 10.5

Reading a map setting

A JSON setting such as MapSettings:DefaultZoomLevel can be read with builder.Configuration["MapSettings:DefaultZoomLevel"]. The same IConfiguration value can be injected into an endpoint handler. section 10.2.1

Listing 10.3 Loading appsettings.json by clearing the configuration sources
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
 
builder.Configuration.Sources.Clear();                                  #1
builder.Configuration.AddJsonFile("appsettings.json", optional: true);  #2
 
WebApplication app = builder.Build();
 
app.MapGet("/", () => app.Configuration.AsEnumerable());                #3
 
app.Run();
#1 Clears the providers configured by default in WebApplicationBuilder
#2 Adds a JSON configuration provider, providing the name of the configuration file
#3 Returns all the configuration key-value pairs for display purposes

Shows how to clear the default providers, add an optional JSON file, and return the resulting key-value pairs. section 10.2.1

How ASP.NET Core in Action, 3e covers it

How deep it goes
Explains provider aggregation, precedence, nested keys, and dependency-injection access, but does not cover strongly typed configuration binding.
Examples
Uses appsettings.json, nested MapSettings values, endpoint injection, and a custom provider list.
What you can do after
Apply it via indexer access or dependency injection to read settings from aggregated configuration sources.
How it connects
Connects IConfiguration with configuration providers, ConfigurationManager, IConfigurationBuilder, IConfigurationRoot, and dependency injection.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of ASP.NET Core in Action, 3e. The section links point to the parts of the book it draws on.