getting db connection through singleton class

前端 未结 6 1778
Happy的楠姐
Happy的楠姐 2020-11-30 02:38

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

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 03:04

    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.

提交回复
热议问题