Situation: What I'd like to do is have access to the data context for the life cycle of a page. This is primarily to (a) avoid series of using() and to avoid (b) out of scope exceptions in the view when a lazy loaded property is accessed.
Edit: I'm using MVC 4 and Entity Framework 4.3.1 (the latest)
What I typically do is
using (MyDB b = new MyDB()) {
...do all my stuff
}
In my controller or the data layer. The nice thing about this, based on my reading, is it's clean, causes no memory leaks etc. But the disadvantage is that even for the lifecycle of a single page I end up doing this again and again, and my objects lose context in the view as I've already disposed of the context.
I did some reading and found a similar post from 2009 but with no code in the answer. Surely some others have figured out how to solve this - I figure I have to do something with
Application_BeginRequest and EndRequest
But I'm just not sure how, and what the gotchas/best practices are.
Thank you for your help (with some code sample if possible!)