ASP.NET MVC Controller Lifecycle

C#asp.net Mvc

C# Problem Overview


It's my understanding that the constructor for a controller is not called during each web request. Assuming this is true, what is the lifecycle of a controller? Is is "constructed" upon app start, then cached and invoked with the requestcontext injected into it with each web request?

Just to be clear, I'm not asking how to emulate constructor behavior, I use the OnActionExecuting event to initiate things I would normally do in a constructor. Also, I do use constructors on controllers for unit and system testing.

Thanks!

C# Solutions


Solution 1 - C#

If you use the default controller factory a new instance will be constructed for each request and that's the way it should be. Controllers shouldn't be shared among different requests. You could though write a custom factory that manages the lifetime of the controllers.

Solution 2 - C#

I'm afraid, your understanding is wrong. A controller (which should be a very thin and lightweight class and must not have any session-outliving state) is actually constructed on the fly for each and every web request. How else could a controller instance be specific to a certain view?

So there is no such thing as a "lifecycle" (other than that of the request)...

Solution 3 - C#

A controller is created for every request you do. Lets 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 passing a username. Don't hope to get the userName you set in the next request. it will return null. Thus for every request a new controller is created. You don't instantiate a controller anywhere in MVC like you instatiate an object from a class. Simply you don't have controller object memory pointer to call it as you do with other objects.

Go to this link. There is a good explanation on lifecycle of MVC controller.

https://stackoverflow.com/questions/16647969/asp-net-mvc-request-life-cycle

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJosh PearceView Question on Stackoverflow
Solution 1 - C#Darin DimitrovView Answer on Stackoverflow
Solution 2 - C#Thomas WellerView Answer on Stackoverflow
Solution 3 - C#Hareendra Chamara PhilipsView Answer on Stackoverflow