Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Configuration Settings in ASP.NET Core

RSS
Modified on Wed, Mar 31, 2021, 7:23 AM by Administrator Categorized as Uncategorized

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;
    }
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2021, Patrick Jasinski.