Home > Back-end >  Implementation of the Singleton pattern on the sql-connection class in c#
Implementation of the Singleton pattern on the sql-connection class in c#

Time:10-26

I learned the singleton pattern recently ,How to implement the Singleton pattern on sql-connection class ? and how to pass the connection details (database name and table name) to each instance of that Singleton ?

CodePudding user response:

I try to implement it by this way:

public  class SqlConnection
{
    private static Dictionary<string, SqlConnection> _InsDictionary = new Dictionary<string, SqlConnection>();
    private string _databaseName;
    private string _tableName;
    private SqlConnection(string databaseName,string tableName)
    {
        _databaseName = databaseName;
        _tableName = tableName;
    }
    public static SqlConnection Ins(string databaseName,string tableName)
    {
        if (_InsDictionary.TryGetValue($"{databaseName}_{tableName}",out var ins))   
        {
            ins = new SqlConnection(databaseName,tableName);
            _InsDictionary.Add($"{databaseName}_{tableName}",ins);
        }
            
        return ins;
    }
}

   void Main()
    {

        SqlConnection sqlConnectionA = SqlConnection.Ins("db1","tb1");
        SqlConnection sqlConnectionB = SqlConnection.Ins("db1","tb2");
            
    }
  • Related