Reputation: 33850
Suppose you do not have control over object creation and disposal. There are some circumstances where you don't.
Take the instance of MVC. Suppose you had something like this:
interface IFoo : IDisposable { }
class HomeController
{
private IFoo _foo = null;
HomeController(IFoo foo)
{
_foo = foo;
}
ActionResult Index()
{
return View(_foo);
}
}
Once your object is passed to the View, you pretty much lose control over it.
In this case, I can only think of two ways to mitigate this scenario:
1) If it hurts, don't do it. In other words, don't let what you give to your views be IDisposable
s.
2) Or, same as 1 but if you do receive an IDisposable
and you want to pass it to the view, don't pass the IDisposable
as such. Cast, even if it involves a copy of all data, to something that's not IDisposable
and call the Dispose()
yourself. For e.g. like so:
ActionResult Index()
{
using(_foo)
{
return View((FooViewModel)_foo);
}
}
But I am curious. Does MVC check for IDisposable
and call it on any state received by the View once it is done rendering the View?
Upvotes: 5
Views: 1811
Reputation: 245429
The ASP.NET MVC Controller
class already implements IDisposable
. If you have further cleanup that needs done after the request executes, you can override the Dispose
method. In your example, it would look something like:
public class HomeController
{
private IFoo _foo = null;
// Your code as usual
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
if(disposing && _foo != null)
_foo.Dispose();
}
}
Upvotes: 4
Reputation: 77637
So, there's a few things here. Short answer: no, MVC will not call Dispose on your view model that's stored in a field.
Longer answer: from what you have listed here, probably.
I'm assuming you are using a some sort of dependency injection framework like autofac, structuremap, etc, then the container will be tracking that instance. I don't know the intricacies of each framework, but I'd assume that many of them do in fact call dispose on your types that implement IDisposable
at the end of the request (autofac does for sure).
In the end, you'll just need to test whether it is or not and go from there.
Upvotes: 3