views:

45

answers:

2

So normally I just put my sql connection string in my asp.net web.config and reference it whenever I need to open a database connection, however this leaves me with referencing it all over my project. This also exposes my sql connection username and password in my web.config if it isn't encoded.

What are you best practices as far as keeping the connection methods in a class or class library? I saw a php tutorial that did this really well (but I can't find it again) and allowed for re-usability.

+4  A: 

I would always keep the connection string in the web.config since the servers/database connections can always change, even if it's not common. To make it more comfortable to view in code you can always add something like this :

String m_Connection = ConfigurationManager.AppSettings["MyConnectionString"];

and then just reference m_Connection everywhere.

I would also always encrypt the connection string using an EncryptionProvider.

Great MSDN article : How To: Encrypt Configuration Sections in ASP.NET 2.0 Using DPAPI

gillyb
What if I created a static class that returned the string, that way if I renamed "MyConnectionString" to something else I would only have to do it once. Does that make sense? Thank you btw!
drpcken
If you create a static class that returns the string, and then want to change "MyConnectionString" to something else, that means you would have to change the string inside the class, meaning you need to compile again. If you don't want your app to suffer from downtime or a new installation, i wouldn't keep this in a compiled class, and i would avoid changing configuration strings like this altogether.
gillyb
Sorry to bring this back up, but you mean putting `m_Connection` in a library? Can I make it static so I don't have to say instantiate it everywhere? I'd love to be able to just say `ConnectionString = m_Connection` anytime I wanted without having to instantiate it.
drpcken
A: 

I agree with @gillyb. In most cases the web.config is the place for the connection string(s). The other common alternative is a spring.Net config file if you make heavy use of dependedncy injection. The end result is the same except that the site will not rebuild if you change the Spring.config file, whereas it will if you change web.config.

Daniel Dyson