Would MVC call Dispose if your ViewModel was IDisposable?
.net, asp.net-mvc, c#, idisposable
Solution
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();
}
}
Problem
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?