I think some of my understanding of MVC is fatally flawed. I've always assumed that the action methods in a controller are stateless AND the controller itself is stateless.
So, is a new instance of the controller created every time any action is called?
It is entirely reasonable to have state in the controller. I usually reference my database connection from a common controller base class. For that reason MVC creates a fresh controller for each request and properly disposes of it at the end.
A new instance of the controller is created for every request coming in. Consider this:
public class HomeController : Controller
{
public ActionResult Index()
{
return MoreIndex();
}
public ActionResult MoreIndex()
{
return View();
}
}
A request coming in for /Home/Index
will enter two actions, but only one controller is created. A request coming in for /Home/MoreIndex
will enter one action and one controller is created. Now nothing prevents you from manually creating a controller and keeping it alive and re-using it. But it will never be in the context of an actual request coming from HTTP.
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