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.
The life cycle is basically is set of certain stages which occur at a certain time. MVC actually defined in two life cycles, the application life cycle, and the request life cycle. The Starting point for every MVC application begins with routing.
ASP.net MVC will automatically expire the value of tempdata once consecutive request returned the result (it means, it alive only till the target view is fully loaded).
The ASP.NET MVC Process. In a MVC application, no physical page exists for a specific request. All the requests are routed to a special class called the Controller. The controller is responsible for generating the response and sending the content back to the browser.
Controller is a class that handles user requests. It retrieves data from the Model and renders view as response. The ASP.NET MVC framework maps requested URLs to the classes that are referred to as controllers.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With