skip to Main Content

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?

2

Answers


  1. Assuming you have a connectionstrings section in your appsettings.json, you can use the GetConnectionString() method on the IConfiguration.

    connectionString = configuration.GetConnectionString("DefaultConnection");
    

    https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.configuration.configurationextensions.getconnectionstring?view=dotnet-plat-ext-6.0

    Login or Signup to reply.
  2. 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);
            }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search