Is using a singleton for the connection a good idea in ASP.NET website

Using a single connection is an extremely bad idea – if access to the connection is properly locked, it means that ASP.NET can only serve one user at a time, which will seriously limit your application’s ability to grow.

If the connection is not properly locked, things can get really weird. For example, one thread might dispose the connection while another thread is trying to execute a command against it.

Instead of using a single connection, you should just create new connection objects when you need them, to take advantage of connection pooling.

Connection pooling is the default behavior for the SqlClient classes (and probably other data providers). When you use connection pooling, any time you ‘create’ a connection, the connection will actually be pulled from a pool of existing ones so that you don’t incur the costs of building one from scratch each time. When you release it (close it or dispose of it) you return it to the connection pool, keeping your total count of connections relatively low.


Edit: You’ll see the error you mention (The timeout period elapsed prior to obtaining a connection from the pool) if you’re not closing (or disposing) your connections. Make sure you do that as soon as you’re done using each connection.

There are several good stack overflow questions that discuss this, which I suspect might be helpful!

Leave a Comment