Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 Development Tools
 ASP.NET
 Singleton Connection Pool

Author  Topic 

OBINNA_EKE
Posting Yak Master

234 Posts

Posted - 2006-12-21 : 01:04:56
I have several Functions that opens & closes connection after interaction, a friend told me that opening/closing connection is very bad that i should implement singleton class to mannage the connection such that opening and closing will be minimised, this is what I wrote
Is it the best way?
if not, pls provide code
Thanks

namespace PropertyApp
{
public class Connection
{
private static SqlConnection myConn = null;
public Connection()
{
//
// TODO: Add constructor logic here
//
}

public static string GetConnection()
{
return System.Configuration.ConfigurationSettings.AppSettings["ConnString"].ToString();
//return "///Data Source=laptop;Initial Catalog=Property;Integrated Security=True";

}

public static SqlConnection GetConn()
{
if (myConn != null)
{
if (myConn.State == ConnectionState.Open)
{
return myConn;
}
else
{
myConn.Open();
return myConn;
}
}
else
{
myConn = new SqlConnection(PropertyApp.Connection.GetConnection());
myConn.Open();
return myConn;
}
}


}
}



If it is that easy, everybody will be doing it

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2006-12-21 : 01:11:07
Keeping a singleton connection is bad practice!
What happens if the connection is broken AFTER user has fetched records but BEFORE user wants to save the edited records?

Open a connection only when needed and close immediately afterwards.
The time spent for open and close (some 10 ms) is not noticable for end-user.
You have better control over error detecting process this way too.


Peter Larsson
Helsingborg, Sweden
Go to Top of Page

dfiala
Posting Yak Master

116 Posts

Posted - 2006-12-21 : 01:25:05
ADO.NET handles connection pooling for you under the covers if you use the same connection string. There is no need to do it yourself. Check out http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconconnectionpoolingforsqlservernetdataprovider.asp.

Peter's advice is correct. Open-use-close your connections.

Dean Fiala
Very Practical Software, Inc
Now with Blogging...
http://www.vpsw.com/blogbaby
Microsoft MVP
Go to Top of Page
   

- Advertisement -