SqlConnection Singleton
Greetings, I would like to ask if creating Singleton to have only one active connection to db is a good idea. What i would like to do is: 1) I have a wcf service 2) wcf service gets data from db 3) i would like to create a singleton like this to have only one connection to db:
private static PersistanceSingleton _Instance;
public static PersistanceSing开发者_JS百科leton Instance
{
get
{
if (_Instance == null)
{
_Instance = new PersistanceSingleton();
}
return _Instance;
}
}
I know this is not an ideal singleton but i just wrote it for this post purpose. I would like to have some persistance repositories here and which I will be instantiating them in constructor. Inside my service class I would have the following code inside constructor
_DBPersistanceSingleton = PersistanceSingleton.Instance;
Then when some request comes (e.g. GetUsersRequest) i would like to do something like:
_DBPersistanceSingleton.GetUsers()
Before each call to db is executed I will also check whether SqlConnection is open or not. Please let me know if this is a good practice. The reason why I think about this solution is because of large number of users that will be connecting to that service via client application
It's not a good practice to reuse SqlConnection
like that. Open it when you need it and close it as soon as you're done with it. Connection pooling will work for you under the hood reusing the connection.
No, I'd strongly recommend you don't. What happens if multiple requests come in at the same time? They can't all use the same connection at the same, at best you'd just be introducing a big bottleneck.
Connection pooling is handled automatically for you, and takes the hassle away from you so you don't need to worry about it. Just open and close connections as needed.
Putting the sql connection aside...
This singleton pattern is not thread safe and is a bad idea to use in a multi-threaded application (as your WCF service is likely to be).
With this code, if multiple simultaneous requests arrive, it is possible that multiple instances will be created.
精彩评论