dev
dev

Reputation: 135

.NET 6.0 - read appsettings.json values from class library

.NET 6.0 - get appsettings.json values from class library. I have a .NET 6.0 web api project and another is class library.

I want to read some settings into class library.

We have appsettings.json inside a web api project. How can I read those values inside a class library?

Could you please provide me proper code snippets

I am new to .net core 6 and also dependency injections and all

Upvotes: 12

Views: 14086

Answers (2)

Isaiah Ryman
Isaiah Ryman

Reputation: 67

Note that if your class library has its appsettings.json at the base directory, you can do this:

public class ConnectionStringProvider : IConnectionStringProvider
{
    public string ConnStrName1 { get; set; }
    public string ConnStrName2 { get; set; }
    public string ConnStr1 { get; set; }
    public string ConnStr2 { get; set; }
    public string Connstr3 { get; set; }
    public IConfigurationRoot configuration { get; set; }

    public ConnectionStringProvider()
    {
        configuration = new ConfigurationBuilder()
        .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
        .AddJsonFile("appsettings.json")
        .Build();
        ConnStrName1 = "ConnectionStringName1";
        ConnStrName2 = "ConnectionStringName2";
        ConnStr1 = configuration.GetConnectionString(ConnStrName1);
        ConnStr2 = configuration.GetConnectionString(ConnStrName2);
        Connstr3 = configuration.GetConnectionString("LocalConnStringName");
    }
}

Upvotes: 1

mnc
mnc

Reputation: 558

In your class library where you want to read in the values, you should be able to access the json-file with ConfigurationBuilder. First, define location of appsettings.json:

string filePath = @"C:\MyDir\MySubDirWhereAppSettingsIsLocated\appSettings.json"; //this is where appSettings.json is located

Then use the filePath when trying to access file:

IConfiguration myConfig = new ConfigurationBuilder()
   .SetBasePath(Path.GetDirectoryName(filePath))
   .AddJsonFile("appSettings.json")
   .Build();

Then afterwards, you can access the individual values inside appsettings.json like this:

string myValue = myConfig.GetValue<string>("nameOfMyValue");

Beware that you need to import the NuGet-package Microsoft.Extensions.Configuration.Json

Upvotes: 4

Related Questions