Configuration Settings in ASP.NET Core

Overview

This article provides and extension method to be used with dependency injection to map a configuration file section to a class.

Code

public static class ConfigurationExtensions
{
    public static TConfig MapConfigSection<TConfig>(this IServiceCollection services, IConfiguration config, string name)
        where TConfig: class
    {
        var settings = config.GetSection(name).Get<TConfig>();
        services.AddSingleton(settings);
        return settings;
    }
}

Usage

Startup.cs

Include the following code your Startup.cs file.

services.MapConfigSection<PowerBISettings>(config, "PowerBI");

Dependency Injection

To inject the dependency on the configuration class ("PowerBISettings" in the above example), include it as a parameter to the constructor. When doing so, be sure to prefix it with the "[FromServices]" attribute, as shown in the following sample code.

public class MySampleClass
{

    private PowerBISettings _powerBiSettings;

    public MySampleClass(
        [FromServices] PowerBISettings powerBiSettings
        )
    {
        _powerBiSettings = powerBiSettings;
    }
}