Actions without statelessness, but are the controllers idle?

I think part of my understanding of MVC is deadly wrong. I always assumed that the action methods in the controller have no state, and the controller itself has no state.

So, is a new controller instance created each time an action is called?

+7
c # asp.net-mvc
source share
2 answers

A new controller instance is created for each incoming request. Consider this:

public class HomeController : Controller { public ActionResult Index() { return MoreIndex(); } public ActionResult MoreIndex() { return View(); } } 

The incoming request for /Home/Index introduces two actions, but only one controller is created. The request included in /Home/MoreIndex will go into one action and one controller will be created. Now, nothing prevents you from manually creating a controller, maintaining it, and reusing it. But this will never be in the context of the actual request coming from HTTP.

+4
source share

In the controller, it is wise to have a state. I usually refer to my database connection from the base class of the common controller. For this reason, MVC creates a new controller for each request and correctly manages it at the end.

+1
source share

All Articles