Reputation: 11330
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?
Upvotes: 2
Views: 417
Reputation: 55032
u need to dispose the context (ie: IDisposable), and i would recommend you to use a DI container, inject your unit of work into that, and set the lifetime per request.
You can call savechanges many time during life time of request. then the convenience that comes with unit of work is gone, whereas if u call only once at the end of the request, you reduce RTT, latency etc.
Upvotes: 1
Reputation: 171178
You probably should have one context per request. The context should be disposed at the end of it.
It might be necessary to use a second context during the request for special purposes like logging (you always want to save log items, even if the main request context is never used for saving).
Upvotes: 1
Reputation: 364279
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.
What other methods? Context provides both commit (SaveChanges
) 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?
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 SaveChanges
calls) 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_BeginRequest
and dispose it in Application_EndRequest
.
Upvotes: 1