It's best to utilize .NET Core dependency injection and let it run magic, this approach is more testable and it doesn't need extra logic and packages inside the class library.
Let's say your appsettings.json
file looks like this -
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"ConnectionStrings": {
"Default": "<CONNECTION_STRING_HERE>"
}
}
Create a non-static class to hold those app-configurations -
public class AppConfiguration
{
public string ConnectionString { get; }
public AppConfiguration(string connectionString)
{
ConnectionString = connectionString;
}
}
Post doing that in the Startup.cs file ConfigureServices
method register the instance as a singleton like this -
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton((provider) =>
{
AppConfiguration c = new AppConfiguration(Configuration.GetConnectionString("Default"));
return c;
});
}
Now lastly you can inject it in the constructor and .NET core IOC container will inject the instance for you.
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
private readonly AppConfiguration _appConfiguration;
public WeatherForecastController(ILogger<WeatherForecastController> logger, AppConfiguration appConfiguration)
{
_logger = logger;
_appConfiguration = appConfiguration;
}
}