Access from class library to appsetting json in asp net core

Introduction

ASP.NET is a popular language used for building web applications. One common that developers face is accessing .json from a class in ASP.NET Core. In this article, we will explore different approaches to this problem.

1: Using IConfiguration

The IConfiguration interface in ASP.NET Core provides a way to access configuration settings. To access appsettings.json from a class library, you can inject the IConfiguration instance into the class library's constructor.


public class MyClass
{
     readonly IConfiguration _configuration;

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

    public void MyMethod()
    {
        string settingValue = _configuration["SettingKey"];
        // Use the setting value
    }
}

In the above example, the IConfiguration instance is injected into the constructor of the MyClass class. The appsettings.json file can be accessed using the indexer , where “SettingKey” is the key of the desired setting.

Approach 2: Using IOptions

Another approach to access appsettings.json from a class library is by using the IOptions pattern. This pattern allows you to bind configuration settings to strongly-typed classes.

First, a class that represents the configuration settings:


public class AppSettings
{
    public string SettingKey { get; set; }
}

Next, configure the appsettings.json file to bind to the AppSettings class:

Finally, inject the IOptions instance into the class library's constructor:

In the above example, the AppSettings class is bound to the configuration “AppSettings” in the appsettings.json file. The IOptions instance is injected into the constructor of the MyClass class, and the setting value can be accessed through the strongly-typed AppSettings object.

Conclusion

Accessing appsettings.json from a class library in ASP.NET Core can be achieved using either the IConfiguration or IOptions approach. Both approaches provide a way to access configuration settings in a flexible and maintainable manner. Choose the approach that best suits your project's requirements and coding style.

Rate this post

Leave a Reply

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

Table of Contents