Awhile back I read a blog post stating that you shouldn't dispose of a data context in a controller action, like this:
using (dataContext)
{
var table = dataContext.GetTable();
var products = from p in table select p;
return View("List", p);
} The argument was that ObjectDisposedExceptions will occur because the data context will be disposed before the view is ever processed by the controller. The blog poster argued that it wasn't really necessary since the data context managed connections internally.
I disagree. I worry that:
- If an exception occurs within the data context, there's no guarantee that the data context will be able to close the collection gracefully. If a number of exceptions occur within a short period of time, on a busy site this could effectively cause it to become unresponsive.
- There's no "contract" that specifies the connection will always be closed when I assume it will be. The MSDN LINQ to SQL FAQ states that the database connection can remain open with certain connection string settings.
In any event, I'm using LINQ to Entities, but I believe the same issues apply.
I ended up putting on my "Classic .NET Hat" and wrote:
public abstract EntityController : System.Web.Mvc.Controller
{
private MyObjectContextClass entities;
protected EntityController()
{
}
protected MyObjectContextClass Entities
{
get
{
if (this.entities == null)
{
this.entities = new MyObjectContextClass();
}
return this.entities;
}
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if (disposing && this.entities != null)
{
this.entities.Dispose();
}
}
}All of my controllers that use that specific Entity Model inherit from this base class, giving me extremely convenient access to the entities while allowing MVC to safely dispose it. Putting a breakpoint into the Dispose method does seem to indict that the controller instance is created and disposed for each request - is this definitely the case, and is this a good solution to the problem?