[ACCEPTED]-ASP MVC: When is IController Dispose() called?-idisposable

Accepted answer
Score: 71

Dispose is called after the view is rendered, always.

The 5 view is rendered in the call to ActionResult.ExecuteResult. That's 4 called (indirectly) by ControllerActionInvoker.InvokeAction, which is in turn 3 called by ControllerBase.ExecuteCore.

Since the controller is in the 2 call stack when the view is rendered, it 1 cannot be disposed then.

Score: 37

Just to expand on Craig Stuntz's Answer:

The ControllerFactory 27 handles when a Controller is disposed. When 26 implementing the IControllerFactory interface, one 25 of the methods that needs to be implemented 24 is ReleaseController.

I am not sure what 23 ControllerFactory you are using, whether 22 you rolled your own, but in Reflector looking 21 at the DefaultControllerFactory, the ReleaseController 20 method is implemented like so:

public virtual void ReleaseController(IController controller)
{
    IDisposable disposable = controller as IDisposable;
    if (disposable != null)
    {
        disposable.Dispose();
    }
}

An IController 19 reference is passed in, if that controller 18 implements IDisposable, then that controllers 17 Dispose method is called. So, if you have 16 anything you need disposing after the request 15 is finished, which is after the view is 14 rendered. Inherit off of IDisposable and 13 put your logic in the Dispose method to 12 release any resources.

The ReleaseController 11 method is called by the System.Web.Mvc.MvcHandler 10 which handles the request and it implements 9 IHttpHandler. The ProcessRequest takes 8 the HttpContext given to it and starts the 7 process of finding the controller to handle 6 the request, by calling into the implemented 5 ControllerFactory. If you look in the ProcessRequest 4 method you will see the finally block which 3 calls the ControllerFactory's ReleaseController. This 2 is only called when the Controller has returned 1 a ViewResult.

More Related questions