PDA

View Full Version : سوال: Singleton Pattern for Database Access



farnaz_s
شنبه 26 بهمن 1387, 12:22 عصر
وقتی از singleton pattern برای ارتباط با DB استفاده میکنیم .چه جوری می شود connection

را close کردو دوباره open کرد؟

Rezaoli
یک شنبه 27 بهمن 1387, 00:25 صبح
فکر کنم اگه یک flag برای باز و بسته بودن connection تعریف کنی، بتونی با چک کردن اون، connection رو باز کنی و ببندی.
اما حالا خودمونیم، چون نمیشه dispose کردش، اصولاً اینجا singleton بدرد نمی خوره فکر کنم.

Sorenaa_s
دوشنبه 28 بهمن 1387, 23:40 عصر
publicclass ConnectionManager
{
private Hashtable _cache = new Hashtable();
privatestatic ConnectionManager _instance = null;

private ConnectionManager()
{
}


publicstatic ConnectionManager Instance
{
get
{
if( _instance == null )
_instance = new ConnectionManager();
return _instance;
}
}


public IDbConnection GetConnection()
{
IDbConnection cnn = null;
if(_cache.Contains(Thread.CurrentThread))
{
cnn = _cache[Thread.CurrentThread] as IDbConnection;
}
else
{
cnn = CreateConnection();
}
_cache[Thread.CurrentThread] = cnn;
if( cnn.State == ConnectionState.Open)
cnn.Open();
return cnn;
}

publicvoid FreeConnection()
{
IDbConnection cnn = _cache[Thread.CurrentThread] as IDbConnection;
if(cnn != null)
{
cnn.Close();
// if neeeded
//_cache.Remove(Thread.CurrentThread);
//cnn.Dispose();
}
}


private IDbConnection CreateConnection()
{
//return new SqlConnection("");
returnnull;
}
}