Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Actions are stateless but are controllers stateless?

Tags:

c#

asp.net-mvc

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?

like image 629
Doug Chamberlain Avatar asked Jul 18 '13 14:07

Doug Chamberlain


2 Answers

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.

like image 44
usr Avatar answered Nov 09 '22 22:11

usr


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.

like image 147
Simon Belanger Avatar answered Nov 09 '22 23:11

Simon Belanger