ASP.NET MVC Controller Life Cycle

I understand that the constructor for the controller is not called during every web request. Assuming this is so, what is the controller life cycle? Is "designed" when the application starts, then it is cached and called with the context request entered into it with every web request?

To be clear, I am not asking how to emulate constructor behavior, I am using the OnActionExecuting event to trigger actions that I would normally do in the constructor. In addition, I use constructors on controllers to test modules and systems.

Thank!

+50
c # asp.net-mvc
Nov 19 '09 at 14:45
source share
3 answers

If you use the factory default controller , a new instance will be created for each request and will be what it should be. Controllers should not be shared between different requests. You could write a custom factory that controls the lifetime of the controllers.

+73
Nov 19 '09 at 15:03
source share

I'm afraid your understanding is wrong. The controller (which should be a very thin and light class and should not have any session waiting state) is actually built on the fly for each web request. How else can a controller instance be specific to a particular view?

So there is no such thing as a "life cycle" (other than a request) ...

+10
Nov 19 '09 at 15:10
source share

A controller is created for each of your requests. Let's take an example.

public class ExampleController : Controller{ public static userName; public void Action1(){//do stuff} public void Action2(){//do stuff} public void AssignUserName(string username){ userName = username; } public string GetName(){ return userName;} } 

Now you can call the controller from the view that passes the username. Do not expect to get the username that you specified in the following query. it will return null. Thus, a new controller is created for each request. You do not instantiate the controller anywhere in MVC, as you install an object from a class. It’s just that you don’t have a memory pointer for the controller object to call it the same way as with other objects.

Follow this link. There is a good explanation of the life cycle of an MVC controller.

ASP.Net MVC - Life Cycle Request

+1
Apr 30 '14 at 9:29
source share



All Articles