Instantiating a context in LINQ to Entities
Creating a new ObjectContext each time does involve 'some' overhead. Essentially the overhead involved is copying metadata from a global cache into metadata associated with the specific ObjectContext.
This overhead is relatively minor, so often it is not worth worrying about, especially when you consider the extra safety inherent in the using pattern.
For me which option you choose depends upon things like:
- How long lived is your wrapping class likely to be? If it lives for a long time the ObjectContext might grow to hold a lot of entities slowing down over time. So a new ObjectContext each time might be a good idea.
- Are calls to the methods on your wrapping class synchronized? The ObjectContext class itself is not threadsafe so if you use the second pattern you need to make sure your wrapping class / repository is thread safe if you expect multiple threads to call it.
- Are the methods essentially unrelated? If so you might get unexpected side-effects if they share one context between the methods.
In general my recommendation is that if the methods are stateless, i.e. fire and forget a new context for each method is probably a good idea.
If however you have a relatively short lived stateful form or something then maybe a shared context is a better idea.
UPDATE: I've taken the time to put together a more complete answer