I’m using Linq to Entities and lately, I found that a lot of folks recommending wrapping the datacontext in a using statement like this:
Using(DataContext db = n
As others have mentioned, it's important for the data contexts to be disposed. I won't go into that further.
I see three possible designs for the class that ensure that the contexts are disposed:
rCustomer
that needs it so that each datacontext is in a using
block.rCustomer
implement IDisposable so that when rCustomer
is disposed you can dispose of it's data context. This means that all rCustomer
instances will need to be wrapped in using
blocks.rCustomer
through its constructor. If you do this then rCustomer
won't be responsible for disposing of it, the user of the class will. This would allow you to use a single data context across several instances of rCustomer
, or with several different classes that need access to the data context. This has advantages (less overhead involved in creating new data contexts) and disadvantages (larger memory footprint as data contexts tend to hold onto quite a lot of memory through caches and the like).I honestly think option #1 is a pretty good one, as long as you don't notice it performing too slowly (I'd time/profile it if you think it's causing problems). Due to connection pooling it shouldn't be all that bad. If it is, I'd go with #3 as my next choice. #2 isn't that far behind, but it would likely be a bit awkward and unexpected for other members of your team (if any).