Possible Duplicate:
SqlConnection Singleton
This is the current code:
static SqlConnection CreateConnection() {
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["IMS"].ConnectionString);
return conn;
}
Because the application will only ever need one open connection I’d like to move it into this design pattern. How do I translate the above into the below?
public sealed class Singleton
{
private Singleton()
{
}
public static Singleton Instance { get { return Nested.instance; } }
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
I’ve just picked this pattern from Jon Skeet’s site – just went for the fully lazy version as it sounded like the best choice – might not be the correct one though.
There are very few situations were a singleton pattern is appropiated. You have to be sure that there is a mandatory need of one and only one instance of a class instance. Normally you don’t have this design requirement, but people tend to make it up.
Connections should be released as soon as you’re done with your unit of work. You should not keep a connection open forever so converting your connection to a singleton won’t help to improve your application design.
Connection pooling mechanism manage the complexity for you so you don’t have to worry about performance in relation to open and close connections since this is optimized by design.
Source MSDN