Search code examples
asp.net-mvchttprequestdisposelifecycle

MVC Request Lifecycle - When / If object disposal occur?


Possible Duplicate:
What is the ‘page lifecycle’ of an ASP.NET MVC page, compared to ASP.NET WebForms?

In ASP.NET MVC, I cannot find anything in the numerous "page lifecycle" or "request lifecycle" articles I've read that touches on object disposal. In an action method, if I create a connection to a database (or maybe create a context to EF), does it ever get disposed if I don't explicitly called dispose?

I know that the model binding to the view can require an open connection still (especially if it's serving an EF object with associations) but does it then dispose of everything instantiated during the request? If so, can someone point this documented out to me please?


Solution

  • A new instance to the controller object is created for every request. This means that the reference to this controller is lost once the action is performed. There on it is left to the garbage collector to dispose and close all the resource intense objects.

    So, the best practice is always to close and dispose all the heavy duty objects in the action method itself.

    I understand that the view would require live connections when binding EF objects. Again the best practice here is to enumerate them before binding to the view.

    The answer to your question is - The garbage collector will be responsible for disposing or closing the connection that are left open in action method - And this is a formula for disaster.

    EDIT Note: Controller class implements IDisposable, so it should be disposed after the request is served. However when I checked the source code of DefaultControllerFactory, I couldnt figure any using scope or explicit dispose call.

    reference

    http://aspnetwebstack.codeplex.com/SourceControl/changeset/view/5d4159c85ff6#src/System.Web.Mvc/DefaultControllerFactory.cs