I’ve been trying to find example of EF per request patterns.
I currently create a unit of work for every transaction, however as i’m doing this in a website, It would be much more convenient to extend this on a per request basis.
I already make use of global.asax to determine if a request if from a page and/or postback so all I need to do it add my object to context.items.
The examples I’ve found to date show a wrapper for the context iteself, but there are other methods inside the unit of work that are also needed, such as commit/save and dispose.
I’m unsure of the best place to introduce the unit of work, in the whole scenario – do I simple create a new unit of work after each change,injecting the context?
Also,given the fact that the request will die naturally, do I need to dispose of the context in this scenario?
Anyone seen some examples that fit the bill or offer advice on the above questions?
What other methods? Context provides both commit (
SaveChanges) andDispose.Do you want unit of work? So in most cases you would need just one for every request to save all changes you do as a single “unit”. There may be situations where you need more than one due to some complicated business logic where changes have to be saved independently (and they cannot be simply saved by same context by multiple
SaveChangescalls) but in such case handling context per request will not work and you will have to get back to starting context when it is needed manually – in terms of injection it means injecting context factory instead of context instance where the component responsible for calling the factory to get context instance is also responsible for context’s disposal.If you just need one context per request you can create it in
Application_BeginRequestand dispose it inApplication_EndRequest.