c#中sql-connection类的单例模式实现



我最近学习了单例模式,如何在sql-connection类上实现单例模式?以及如何将连接细节(数据库名和表名)传递给该Singleton的每个实例?

我尝试这样实现它:

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");

}

相关内容

  • 没有找到相关文章

最新更新