tags:

views:

142

answers:

2

How i can use IDisposable interface with asp.net mvc.

+1  A: 

IDisposable in asp.net mvc is the same as IDisposable in other places of .Net framework.

J.W.
A: 

This is not such a bad question as some might think. It's just asked in a wrong way. Consider the following code:

ActionResult UserList()
{
 using (var ctx = new DbCtx())
 {
   return View(ctx.Users)
 }
}

Won't work since ctx is disposed long before view actually iterates over the data resulting in object disposed exception.

Solution would be to dispose of ctx in Controller.Dispose. What is not obvious is that most of dependencies injected into our controllers will have to implement IDisposable sooner or later.

This is not an mvc specific issue though.

Mikeon
This is why I like using Autofac as my controller factory. Injected dependencies automatically have their Dispose method called, if there is one, at the end of the request.
Joel Mueller