Is it considered a good practice to use a single ObjectContext per request? I read these objects should be short lived and are not extremely costly to instantiate but does this make the case appealing for one of them per request? If yes, are there any patterns that properly implement this?
Asked
Active
Viewed 3,798 times
3
-
1Short answer: yes. For more details (patterns...): is this webforms or MVC? – ken2k May 14 '13 at 13:05
1 Answers
5
Yes it is an accepted approach to have ObjectContext/DbContext with lifetimes per HttpRequest. Here's a sample I have provided in another answer.
Hoewever, it's better to leave these lifetime managements to an IoC library. Famous ones are Castle Windsor, Autofac.
Update:
To dispose your context, you can use Application_EndRequest
method in Global.asax. The following code is not tested but you'll get the idea:
protected virtual void Application_EndRequest()
{
var key = "MyDb_" + HttpContext.Current.GetHashCode().ToString("x")
+ Thread.CurrentContext.ContextID.ToString();
var context = HttpContext.Current.Items[key] as MyDbContext;
if (context != null)
{
context.Dispose();
}
}
-
It seems a bit complicated to use an IOC with webforms. Since i have a small application, I think i'll go with the solution suggested in the sample you pointed to. so now, is there a way to force the disposal of the request scoped Context object once the request is terminated? – kfc May 15 '13 at 09:48