How to create a global "C#" class for data base connection such that:
1. all classes and controls can handle.
2. remian all session untill the main from of an application closed.
3. disconnect from the server when closing windows Form application
Asked
Active
Viewed 159 times
-1

rene
- 41,474
- 78
- 114
- 152

Diaa Fayed
- 9
- 1
-
2You can use singleton or database pool as described in this topic: [link](http://stackoverflow.com/questions/6507687/should-a-db-connection-be-a-singleton) – Yuri Solodkin Dec 21 '13 at 14:23
-
1"remain all sessions" is a very bad idea, almost a system killer! And there's no such thing as "global" in OOP, the nearest thing are static classes (but not necessarily the best choice for what you intend). – Thomas Weller Dec 21 '13 at 14:25
-
Thomas' points are well-taken... and **very well answered at yursol's link**... where the first answer is very helpful, re' database connection pools. – Doug_Ivison Dec 21 '13 at 15:09
2 Answers
1
Use a Singleton Design pattern. A Singleton ensures there is a global access point to a class and that there is only one instance of the class. It is far superior to a static class. Singleton vs. Static Class.
Singleton
public class Singleton
{
private static Singleton instance;
// Private Constructor.
private Singleton()
{
// This ensures no other class but this can create instances of the Singleton.
}
// Returns the instance of this class.
public static Singleton getInstance()
{
// Check if an instance of this class already exists.
if(instance == null)
// It doesn't exist so create it.
instance = new Singleton();
// Return the instance.
return instance;
}
}

Community
- 1
- 1
-
1Why is a Singleton 'far superior'? After all, it basically _is_ a static class. Could you elaborate on that? – Thomas Weller Dec 21 '13 at 14:48
-
I will post a link just for you (This has been covered extensively, I wanted OP to research). I will give you a very practical example though. What if you want to change your class from static to non-static, how many functions will you have to edit-out the `static` keyword. – Dec 21 '13 at 14:51
1
You can try using Singleton design pattern
http://en.wikipedia.org/wiki/Singleton_pattern
Typical thread-safe implementation can be like this:
public sealed class Program {
private static Object s_SyncObj = new Object();
private static volatile Program s_Instance;
private Program() {
...
}
public static Program Instance {
get {
if (!Object.ReferenceEquals(null, s_Instance))
return s_Instance;
lock (s_SyncObj) {
if (!Object.ReferenceEquals(null, s_Instance))
return s_Instance;
s_Instance = new Program();
}
return s_Instance;
}
}
}
You can also try using just a static class:
public static class Program {
...
}

Dmitry Bychenko
- 180,369
- 20
- 160
- 215