Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decouple connection string from Backend code

Tags:

c#

sql

I have a DB connection string stored in web.config. I am creating a common library that requires the connection string. I could pass it in

Utility utilityToConnectToDb = new Utility("conString");

But, I have classes in the Library that call Utility. So I'll also need to give them knowledge of the connection string. This seems sloppy.

I am considering adding an XML file to the library and storing the connection string in this file.

Any better ideas or generally well accepted ways to solve this problem?

like image 585
P.Brian.Mackey Avatar asked Aug 04 '26 03:08

P.Brian.Mackey


1 Answers

it is difficult to maintain connections in library projects, easy way is access web config connection string from other libraries. add one util method to take the connection...

   private string GetWebConfigConnection()
    {

        string conString = string.Empty;
        System.Configuration.Configuration rootWebConfig =
            System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("/WebSite21"); // give your web site name here

        System.Configuration.ConnectionStringSettings connString;
        if (rootWebConfig.ConnectionStrings.ConnectionStrings.Count > 0)
        {
            connString = rootWebConfig.ConnectionStrings.ConnectionStrings["MainConnStr"]; // give your connection string name here
            if (connString != null)
                conString=  connString.ConnectionString;
        }

        return conString;
    }
like image 118
Damith Avatar answered Aug 06 '26 16:08

Damith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!