I have client-server application, where server side is Azure WCF service with data in SQL azure database. Clients are Windows Phone 7 silverlight applications. Client and server communicate throught WCF. Server is providing data to client which are stored in Azure SQL database.
I recently ran to some problems with pooling. I was creating new object every time when client request arrived. I was not closing this connections and very soon encountered exception:
Timeout expired. The timeout period elapsed prior to obtaining a
connection from the pool. This may have occurred because all pooled
connections were in use and max pool size was reached.
My question is – how should connection object to DB be handled? Should i create one connection object for every client request or should i create singleton object which should handle all calls to db? IS it even possible – does not connection object time out after some time or something?
I am using SQLConnection object:
private static SqlConnection connection
{
get
{
SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder
{
DataSource = DB_SOURCE,
InitialCatalog = DB_NAME,
Encrypt = false,
TrustServerCertificate = false,
UserID = DB_USER,
Password = DB_PASS,
};
SqlConnection c = new SqlConnection(connectionStringBuilder.ToString());
c.Open();
return c;
}
}
public static void execute(String query)
{
try
{
SqlCommand com = new SqlCommand(query, connection);
com.ExecuteNonQuery();
}
finally
{
connection.Close();
}
}
I agree with the answers provided by Wiktor Zychla, Tobias, and Herve Roggero. They explain that:
connectproperty), doesn’t return the originalSqlConnectionthat you were expecting, hence the original connection is not getting closed.SqlConnections when you need them, keep them open only as long as you need them, and close them when you are done.Here’s a complete solution: