lifetime management

  • Thread starter Thread starter Jarlaxle
  • Start date Start date
J

Jarlaxle

If I was going to cache some sqlconnection and sqltransaction objects for
lookup from multiple functions...how would you recommend handling the clsoing
and disposing?

i.e. something like the following (shortened for brevity)...

class DBObject : IDisposable
{
public SqlConnection Connection {get; set;}
public SqlTransaction Transaction {get; set;}
public void Dispose()
{
if (Connection != null) Connection.Dispose();
if (Transaction != null) Transaction.Dispose();
}
}

class DBManager
{
private static HashTable<int, DBObject> _dbobjects;

public static DBObject GetDBObject()
{
DBObject dbo = _dbobjects.find(Thread.CurrentThreadID);
if (dbo == null)
{
dbo = new DBObject();
_dbobject.Add(Thread.CurrentThreadID(), dbo);
}
return dbo;
}
}

call comes into server...

void Method1()
{
DBObejct dbo = DBManager.GetDBObject();
...do stuff with it...
Method2();
}

void Method2()
{
DBObject dbo = DBManager.GetDBObject();
...do stuff with it...
}

there are many methods so I can't pass DBObject directly so I need a lookup
method...problem is when it will be removed from the manager list and
disposed of...i suppose i could reference count it but wanted to see if
anyone had other ideas...
 
Why would you want to cache them at all?
You should create them on demand on dispose them asap.
Connection pool will take care of caching connections.
 
Back
Top