What is the lifetime of a ASP.NET MVC Controller?

I'm in the process of developing my MVC application and I was thinking, What is the lifetime of a controller class?

When does it get created? How many instances of a single controller are there? what are the implications of local variables? when is it destroyed?

I'm sure there is a good link somewhere floating around on the internet, but my google-fu couldn't find it.


Solution 1:

Stephen Walther has a great article on the life-cycle of a request being handled by the MVC Framework.

Here's a extract from the top of his article, it goes on to explain each step in detail:

Overview of the Lifecycle Steps

There are five main steps that happen when you make a request from an ASP.NET MVC website:

1. The RouteTable is Created

This first step happens only once when an ASP.NET application first starts. The RouteTable maps URLs to handlers.

2. The UrlRoutingModule Intercepts the Request

This second step happens whenever you make a request. The UrlRoutingModule intercepts every request and creates and executes the right handler.

3. The MvcHandler Executes

The MvcHandler creates a controller, passes the controller a ControllerContext, and executes the controller.

4. The Controller Executes

The controller determines which controller method to execute, builds a list of parameters, and executes the method.

5. The RenderView Method is Called

Typically, a controller method calls RenderView() to render content back to the browser. The Controller.RenderView() method delegates its work to a particular ViewEngine

Solution 2:

Assuming you don't change the default ControllerFactory, controllers will be created for every request and will be garbage collected "sometime after" the request has completed.

In short, you don't need to worry about race conditions for instance variables (though you do for static variables, obviously). Having said that, I'd recommend keeping your controller actions reentrant for the sake of cleaner code.