Friday, April 10, 2020

Access config settings directly from class library

In the previous post we saw on how to access the config settings by creating a custom class and injecting it in the startup, so that it can be used in the controllers. In this case the startup and the controller classes are in the same project.

In an n-tier application we can have multiple layers/projects like Service, Repository, Data Access etc. We will need some of the config settings in these projects. To do this we can pass the required values as parameters from the controller since the controller has access to the configuration class. In this approach we might have to pass the connection string as parameter in many methods. In this post we will see another way by which we can access the configuration settings directly from the class library project.

Connection string is a very common setting which will be needed in the Data Access layer to connect to the database. In this sample we will see how to access a section of the appsettings.json which has the connection string directly in the DataAccess layer class library.

We create a class AppConfiguration, which will read the config file appsettings.json and get the config key/values to the configuration class.

public class AppConfiguration
{
    public readonly string _connectionString = string.Empty;
    public AppConfiguration()
    {
        var configurationBuilder = new ConfigurationBuilder();
        var path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");
        configurationBuilder.AddJsonFile(path, false);

        var root = configurationBuilder.Build();
        _connectionString = root.GetSection("ApplicationSettings").GetSection("ConnectionString").Value;
    }
    public string ConnectionString
    {
        get => _connectionString;
    }
}

In this class we read the configuration settings file appsettings.json through the file system and add the settings to the Configuration Builder, next we read the value for the key ConnectionString from the ApplicationSettings section into the property connectionString. Now the conntectionString property can be accessed anywhere in the class library project.


Search Flipkart Products:
Flipkart.com

No comments: