开发者

Decouple connection string from Backend code

开发者 https://www.devze.com 2023-03-26 11:02 出处:网络
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

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 开发者_JAVA技巧better ideas or generally well accepted ways to solve this problem?


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;
    }


you can put the connection string in to library app.config file as well. then you can use it as you used in the web project.


For changeable items like connection strings, I like building a serializable custom class, and writing a small UI to handle changing the configuration information. This way, if configuration information changes, it's relatively easy to change.

The configuration class can be known to all of the classes of the project. You can encrypt the data and even use hashing to verify the integrity of the values, if you want to go that far.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号