Class Library(.NET Standard) – Read appsetting.json Configuration

Class Library NET Standard Reading apsettingjson

In this article, we will see how to perform .NET Standard Class Library – Read appsetting.json Configuration. We will load the configuration in a class library project or external project (which could be.NET Standards or any other class library or DLL).

So overall in this article, I will talk about the below approaches for reading the configuration. Below discussed approaches leverages dependency injection(DI) and one approach discussed is non-DI.

Today in this article, we will cover below aspects,

I did verify the below above approaches for both ASP.NET Core and Console .NET Core application or Class library(DLL), etc. One can use any approach in any of your project types.

Getting started

I already have a sample application below which consists of the Console app and class library project below,

This application looks like a real project which has the below modules,

  • Application Layer – Could be a Host application like ASP.NET Core or a non-host like Console or Winform or WPF
  • Business Layer – Class library
  • Data Access Layer– Class library

If you need more details DI concept then please go through the below article on DI,

Approach1 – Using IConfiguration Interface

IConfiguration interface is the simplest way of loading the configuration in API or MVC application. This doesn’t require you to write any custom interface etc.

I have ASP.NET Core API with ConfigureServices() method defined as below application as below,

public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddScoped<IBusinessLayer, BusinessLayer>();
            services.AddSingleton<IDataAccessLayer, CDataAccessLayer>();
        }


Above BusinessLayer class and Interface IBusinessLayer is defined in the Class library projects.

With the above provision, the class library instances get loaded into the host application and the DI container defines and registers the instances even from dependency like a class library.

Let’s see now to IConfiguration becomes accessible easily in the class library project without any hassle,

Complete implementation as below,

public class BusinessLayer : IBusinessLayer
    {
        private readonly ILogger _logger;
        private readonly IDataAccessLayer _dataAccess;
        string _URL;

        public BusinessLayer(ILogger<BusinessLayer> logger,
                              IDataAccessLayer dataAccess,IConfiguration config)
        {
            _URL = config["Customer:Common:ServerURL"];
            _logger = logger;
            _dataAccess = dataAccess;
        }

..
..
..
     }

Approach 2 – Using Custom Interface

In this approach, you write your custom interface to load the specific configuration details within the ConfigureServices method and resolve the interface.

This option also provides better control and also helps you create a typesafe configuration that can be transferred to any other modules like the class library or other dependencies in the given application etc.

Example:

NET Standard Class Library Read appsettingjson Configuration

Above I created the ICustomerConfig custom config interface that can be DI in any other module of the application. It can also be injected into the .NET Standards class library as well if your application uses class libraries as dependencies.

NET Standard Class Library Read appsettingjson Configuration

So with the above solution, it becomes very easy to inject the configuration or business services into your project and class libraries as well.

One can use the above solution to load the configuration available in other source files like XML, INI, or other JSON files, etc. as well.

The above approach works in ASP.NET Core based applications out of the box due to inbuilt support for IoC Container where we can inject required services within the API pipeline.

Below is a sample apsettings.json,

{

  "ServerURL": "https://localhost:44347/api/employee",
  "Customer": {
    "CustomerKeyurl": "http://thecodebuzz/key",
    "CustomerdetailsUrl": "http://thecodebuzz/id",
    "Agency": {
      "AgencyID": "subvalue1_from_json",
      "AccountKey": 200
    }
  }
}

If you need to perform dependency injection in the Console application, please go through the below article on DI,

  • Using Dependency Injection in a .NET Core Console/ Desktop Application
  • Approach 3 – Loading configuration without Dependency injection i.e ConfigurationBuilder

    Load any configuration like apsettings.json or .ini or XML or app.config, etc without dependency injection(DI).

    Please see the below article for complete details.

    The above non-DI approach can be used in the below type of applications,

    • Console or
    • Shared Library
    • ASP.NET Core(MVC or API)

    Hope you found this article useful.

    Do you have any comments or ideas or any better suggestions to share?

    Please sound off your comments below.

    Happy Coding !!

    Summary

    Today in this article, we looked at a possible solution for loading the configuration from the apsetting.json file in the class library or external project (which could be.NET Standards or any other class library or DLL). We understood DI can be leveraged to inject the configuration into the class library easily.



    Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.



    6 thoughts on “.NET Standard Class Library – Read appsetting.json Configuration

    1. hi
      thanks for your article may i know the structure of ICustomerConfig and also where it should be placed is it in the Web application layer or is your full code sample available to see
      Thanks in advance

      1. Hello Tariq, Thanks for your query.CustomerConfig is actually derived from above sample Apsettings.JSON a type-safe representation of the configuration file.Please see here for more details

        public class CustomerConfig : ICustomerConfig
        {
        public string CustomerKeyurl { get; set; }
        public string CustomerdetailsUrl { get; set; }
        public Agency Agency { get; set; }
        }

        public interface ICustomerConfig
        {
        string CustomerKeyurl { get; set; }
        string CustomerdetailsUrl { get; set; }
        Agency Agency { get; set; }
        }

      1. Hi Mahmood- Thanks for your query. If you are using IOC using asp.net core, it will be done using constructor injection in the calle side. In the example , I am calling it in the Controller constructor and injecting the business layer. App WorFlow is like Controller->BusinessLayer->DataAccessLayer.

    Leave a Reply

    Your email address will not be published. Required fields are marked *