IConfiguration interface is the heart of the configuration system. It represents a set of key-value pairs that can be loaded from various sources (JSON files, environment variables, etc.). This interface provides a unified way to access your application’s settings, regardless of where they are stored.
Key Methods, Properties, and Indexers GetSection(string key): Purpose: Retrieves a specific section of the configuration as an IConfigurationSection. Sections allow you to group related settings. Example: var connectionStrings = configuration.GetSection(“ConnectionStrings”);
GetValue<T>(string key): Purpose: Retrieves a configuration value as a specified type T. Example: var port = configuration.GetValue<int>(“Server:Port”);
GetConnectionString(string name): Purpose: Retrieves a connection string from the “ConnectionStrings” section of the configuration. Example: var connectionString = configuration.GetConnectionString(“DefaultConnection”);
GetChildren(): Purpose: Returns an enumerable collection of IConfigurationSection objects representing the immediate children of the current section. Example: var sections = configuration.GetSection(“Logging”).GetChildren();
Indexer (this[string key]): Purpose: Retrieves a configuration value as a string. Example: var value = configuration[“Logging:LogLevel:Default”];
Injecting IConfiguration In Controllers: public class HomeController : Controller { private readonly IConfiguration _configuration; // Field to store IConfiguration
public HomeController(IConfiguration configuration) { _configuration = configuration; }
public IActionResult Index() { var myKeyValue = _configuration[“MyKey”]; // Access configuration value return View(); } }
In Services: public class EmailService : IEmailService { private readonly IConfiguration _configuration;
public EmailService(IConfiguration configuration) { _configuration = configuration; }
public void SendEmail(string to, string subject, string body) { var smtpServer = _configuration[“Email:SmtpServer”]; // Use configuration for email settings // … (email sending logic) } } In both cases, the IConfiguration is injected through the constructor using ASP.NET Core’s dependency injection.