I have a library in a large asp.net 4.8 site that uses the ConfigurationManager deep down in the bowels of the project. At the time, no one had a problem with the dependency on that library. Well, we're upgrading to asp.net 5 (i.e. Core) which doesn't really use the ConfigurationManager anymore, instead uses a DI version of IConfguration. Unfortunately the access of the connection strings is so deep, passing along this object from the Controller down through the libraries isn't feasible. Is there any kind of "ConfigurationManager.ConnectionStrings" equivalent that reads the application.json file's ConnectionStrings section?
CodePudding user response:
You can use the following Code
public class SampleClass
{
private readonly IConfiguration _config;
public SampleClass(IConfiguration config)
{
_config = config;
}
public string GetConnectingString(string name)
{
return _config.GetConnectionString(name);
}
}
CodePudding user response:
Assuming you have a connectionstrings section in your appsettings.json, you can use the GetConnectionString() method on the IConfiguration.
connectionString = configuration.GetConnectionString("DefaultConnection");