Question

I saw many developer create singleton class for database connection. I just like to know is it good or evil when application will be used by many users. if not good please discuss all the bad situation may occur for the above pattern.

public class ConnSingleton
{
        private static ConnSingleton dbInstance;
        private readonly SqlConnection conn = new SqlConnection(@"Data Source=127.0.0.1;database=soa;User id=sa1;Password=sa1;");       
     
        private ConnSingleton()
        {
        }

        public static ConnSingleton getDbInstance()
        {
            if (dbInstance == null)
            {
                dbInstance = new ConnSingleton();
            }

            return dbInstance;
        }

        public SqlConnection GetDBConnection()
        {
            try
            {
                conn.Open();
                Console.WriteLine("Connected");
            }
            catch (SqlException e)
            {
                Console.WriteLine("Not connected : "+e.ToString());
                Console.ReadLine();
            }
            finally
            {
                Console.WriteLine("End..");
               // Console.WriteLine("Not connected : " + e.ToString());
                Console.ReadLine();
            }
            Console.ReadLine();
            return con;
        }
}

public static void Main(string[] args)
{
     ConnSingleton cs = ConnSingleton.getDbInstance();
     cs.GetDBConnection();           
     Console.WriteLine("Connection established");
}
Was it helpful?

Solution

I can see nothing good coming from this class. If you want it that way (and I'm not in favor of it) you gained no benefit over a bunch of static methods. What would the singleton instance be good for? How would you put the SqlConnection variable inside a using block?

I think a singleton is a way overused pattern for people that want global variables, but read a book that mentioned the fact globals are bad. Now they found another book stating that "Singleton" is a pattern and patterns are "good" and they finally have an excuse to have a global.

Being a global variable is a side effect of the singleton. If you are using it for the side effect, it's not a good use of the pattern. I would say it's an abuse.

Singletons are almost impossible to unit test. This one is not even thread save and does not have any use over a non-singleton. So from my point of view... delete the class.

How many people use the application is irrelevant. Each will have it's own process and it's own singleton, as bad as that may be.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top