Reputation: 11351
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?
Upvotes: 7
Views: 1344
Reputation: 171216
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.
Upvotes: 1
Reputation: 14880
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.
Upvotes: 4