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 PersistanceSingleton 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
SqlConnectionlike 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.