I have created an singleton class, this class returns a database connection. So my question is this connection is also satisfying singleton criteria?
If no, than how I c
The connection itself is not satisfying the Singleton criteria because you can create multiple instances of a database connection object. A singleton by definition can only be instantiated once.
You can make the SqlConnection a part of the Singleton, by changing your example to this:
public sealed class SingletonDB
{
private static readonly SingletonDB instance = new SingletonDB();
private readonly SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["mydb"].ConnectionString);
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static SingletonDB()
{
}
private SingletonDB()
{
}
public static SingletonDB Instance
{
get
{
return instance;
}
}
public SqlConnection GetDBConnection()
{
return con;
}
}
This way the SqlConnection used by your SingletonDB class would have one and only one SqlConnection, thus follow the Singleton pattern.