문제

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");
}
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top