Proper adapter use

Posts   
 
    
methodman
User
Posts: 194
Joined: 24-Aug-2009
# Posted on: 08-Oct-2010 15:18:48   

Hi,

I have a situation where I'm doing some fetching,processing and saving and again some processing and fetching.

Sample code:

var e = adapter.FetchEntity(..);

var e2 = generateXml(e); 

adapter.SaveEntity(e2);

doSomeProcessing();

adapter.FetchEntityCollection(...);

I read somewhere the best practice for adapter use is to dispose it ASAP. So my question is should I create an adapter for every adapter call or just use one ?

using(var adapter = new DataAccessAdapter)
{
var e = adapter.FetchEntity(..);

var e2 = generateXml(e); 

adapter.SaveEntity(e2);

doSomeProcessing();

adapter.FetchEntityCollection(...);
}

or


using(var adapter = new DataAccessAdapter)
{
var e = adapter.FetchEntity(..);
}
var e2 = generateXml(e); 

using(var adapter = new DataAccessAdapter)
{
adapter.SaveEntity(e2);
}
doSomeProcessing();

using(var adapter = new DataAccessAdapter)
{
adapter.FetchEntityCollection(...);
}

daelmo avatar
daelmo
Support Team
Posts: 8245
Joined: 28-Nov-2005
# Posted on: 09-Oct-2010 03:21:29   

In general, I don't see a big difference between the two options. In both you use the adapter object as a local variable (method scope) and you use "using... " statement. You also are not sharing nor passed the adapter object in the doProcessing() method. So it's very clear that you wont get problems there.

You also are not using transactions, and the DB calls are independent. I would evaluate what doProcessing do. If it's a long processing maybe it's better to use a "using..." statement before processing and another after processing.

As a programmer that doesn't have any clue what processing do, I would prefer this:

using(var adapter = new DataAccessAdapter)
{
var e = adapter.FetchEntity(..);
}

var e2 = generateXml(e); 

using(var adapter = new DataAccessAdapter)
{
adapter.SaveEntity(e2);
}

doSomeProcessing();

using(var adapter = new DataAccessAdapter)
{
adapter.FetchEntityCollection(...);
}

That way, if I need to refactor in the future, it's more clear to me.

David Elizondo | LLBLGen Support Team