Reading appsettings.json in .Net Core Class Library Using Dependency Injection

by GeeksArray

This blog post explains in .net core class library application how to read configuration settings from the web application's appsettings.json file by injecting dependency of IConfiguration interface.

The class library does not have a configuration file by default. Dependency injection is already part of .Net Core, you will have to register your dependencies in the ConfigureService method of Startup.cs file.

Steps to read appsettings.json of a web application to the class library using Dependency Injection

  1. Create ASP.NET MVC Core and Class library

    Create new application by clicking File -> New -> Project -> Installed -> C# -> Web -> ASP.Net Web Core application. Name your web application and click Ok. In new window select Web Application (Model-View-Controller) and click Ok.

    Open solution explorer and right click on the solution and add a new class library project to the solution.

    For Web application and class library you can give names as you like, I added web applications with name GeeksApp and class library with name GeeksConfiguration.

  2. Add connection string and appsettings in appsettings.json

    In this step, you will add custom settings like database connection string or account settings in the appsettings.json file as per the application environment.

    Open appsettings.json file from GeeksApp MVC application and add below configuration.

    
    {
      "Logging": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "ConnectionStrings": {
        "NorthwindDatabase": "Data Source=(localdb)\\ProjectsV13;Initial Catalog=Northwind;
        Integrated Security=True;Connect Timeout=30;"
      },
      "AppSeettings": {
        "EmailID": "geeks@array.com",
        "AccountKey" : "xlymrkar24arla"
      },
      "AllowedHosts": "*"
    }
    
  3. Install Microsoft.Extensions.Configuration NuGet package

    To read Key-Value based configuration you need to install Microsoft.Extensions.Configuration NuGet package. As this package has dependency on Microsoft.Extensions.Configuration.Abstractions so install both NuGet packages by using below commands in Package Manager Console of GeeksConfiguration class library application.

    Install-Package Microsoft.Extensions.Configuration.Abstractions
    
    Install-Package Microsoft.Extensions.Configuration
    
  4. Add Interface for Dependency Injection

    In this step, you will add an Interface in class library application. Interface dependency is used by the client but implemented by the service. You can avoid using interface and inject the service object directly to the client. However doing that, you break the principle of dependency inversion as the client has an explicit dependency on the service class.

    To implement Interface Dependency add a new Interface to class library project with name IGeekConfigManager

    using Microsoft.Extensions.Configuration;
    
    namespace GeeksConfiguration
    {
        public interface IGeekConfigManager 
        {
            string NorthwindConnection { get; }
    
            string EmailID { get; }
    
            string AccountKey { get; }
    
            string GetConnectionString(string connectionName);
    
            IConfigurationSection GetConfigurationSection(string Key);
        }
    }
    
    
  5. Using IConfiguration and IGeekConfigManager

    IConfiguration gives key/value application configuration properties. In this step, you will implement IGeekConfigManager to a class from the class library project. This class will return the required configuration values defined in the appsettings.json file of ASP.NET Core or Console application.

    Add a new class file with the name GeekConfigManager to your class library project. Now implement the IGeekConfigManager interface and add a reference to Microsoft.Extensions.Configuration to the newly created class.

    Add below code to GeekConfigManager with Constructor dependency injection.

    using Microsoft.Extensions.Configuration;
    
    namespace GeeksConfiguration
    {
        public class GeekConfigManager : IGeekConfigManager
        {
            private readonly IConfiguration _configuration;
            public GeekConfigManager(IConfiguration configuration)
            {
                this._configuration = configuration;
            }
        }
    }
    

    This will create a constructor dependency, client class must supply dependency through client constructor.

    Get connection string from appsettings.json

    To read NorthwindDatabase connection string defined in appsettings.json of MVC application you can use two different ways as shown below.

    public string NorthwindConnection
    {
        get
        {    
            return this._configuration["ConnectionStrings:NorthwindDatabase"]; 
        }
    }
    
    public string GetConnectionString(string connectionName)
    {
        return this._configuration.GetConnectionString(connectionName);
    }
    

    The first one uses property and return value for NorthwindDatabase added in the ConnectionStrings section.

    The second one uses the GetConnectionString method of IConfiguration and return value of the connection string depending on the key provided to method as an input parameter.

    Getting specific AppSettings value or a specific section

    You can get specific AppSetting like AccountKey or Email from MVC application to your BAL or DAL class library as shown below

    public string EmailID
    {
        get
        {
            return this._configuration["AppSeettings:EmailID"];
        }
    }
    
    public string AccountKey
    {
        get
        {
            return this._configuration["AppSeettings:AccountKey"];
        }
    }
    
    public IConfigurationSection GetConfigurationSection(string key)
    {
        return this._configuration.GetSection(key);
    }
    

    The property EmailID or AccountKey returns value configured in the appsettings.json file. The GetConfigurationSection returns specific section configured in the appsettings.json file of ASP.NET MVC Core application.

  6. Registering IGeekConfigManager dependency in a service container

    In this step, you will register dependency in service container to access configuration data. Services are registered in the app's Startup.ConfigureServices method.

    Add a reference to Class library dll to your ASP.NET MVC Core application.
    Open Startup.cs file from ASP.NET Core or Console application and add the below code. This is required for class to become available as a configuration object. Register dependency of GeekConfigManager as Singleton.

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        
        services.AddSingleton<IGeekConfigManager, GeekConfigManager>();
    }
    

    As your configuration will rarely change in the production / development environment, we will use services.AddSingleton. This will create a single instance and reuse for each request where ever it is required. At start up of your application, you are telling your application to inject GeekConfigManager implementation where ever IGeekConfigManager is used.

  7. Accessing Strongly Typed Configuration in MVC Controller

    Now you are all set to read configuration settings from appsettings.js through dependency injection where ever you need it. You can inject the dependency of IGeekConfigManager through the HomeController constructor.

    Open HomeController and add constructor as shown. Make sure you have added reference GeekConfiguration dll and used it in HomeController.

    using GeeksConfiguration;
    
    namespace GeeksApp.Controllers
    {
        public class HomeController : Controller
        {
            private readonly IGeekConfigManager _configuration;
    
            public HomeController(IGeekConfigManager configuration)
            {
                this._configuration = configuration;
            }
        }
    }
    

    Now you can read any configuration value in any action method of the controller. Add below code to the Index action method.

    public IActionResult Index()
    {
        string strEmail = this._configuration.EmailID;
        string strAccountKey = this._configuration.AccountKey;
        return View();
    }
    

    This code reads values of EmailID and AccountKey from the appsettings.json file of MVC Core application.

    entity framework core appsettings value dependency injection using interface

Source code on Git hub Source Code on Github

Speak your mind
Please login to post your comment!


  • geeksarray user
    04/30/2021 01:41 AM hari001

    Hi Nice post and can you tell us how to access "GeekConfigManager" from BAL-layer (2 class libraries BAL & DAL) instead of from Controller ?