ASP.NET Core Interview Question #29

What is IConfiguration and how is it used?

Application Structure & Configuration Junior Beginner

Quick Interview Answer

IConfiguration represents the application's configuration data. It provides access to configuration values regardless of which provider supplied them.

Detailed Explanation

IConfiguration represents the application's configuration data. It provides access to configuration values regardless of which provider supplied them.

Values can be accessed using keys, sections, GetValue<T>(), or GetConnectionString(). Nested JSON keys use a colon-separated path such as EmailSettings:Sender.

Direct IConfiguration access is useful for a small number of settings. For related settings used throughout an application, the Options pattern is generally cleaner and more strongly typed.

Code Example

public class ReportService
{
    private readonly IConfiguration _configuration;

    public ReportService(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public int GetPageSize()
    {
        return _configuration.GetValue<int>("Reports:PageSize");
    }
}