I have quite a few things in the constructor of my controller. Is it the case that every time I request a new page with MVC3 then the constructor executes?
A controller instance is required to serve each request. And to obtain this instance (obviously) the controller constructor is called on each request. This being said you should avoid doing many things in this constructor. There are cases for example where for some particular action on this controller you don't need all this initialization and despite this if you put it in the constructor, it will be executed. If the tasks you perform are simply instantiating some other dependencies that your controller needs, then you shouldn't worry about performance, you should worry about properly architecting your application as this job should be handled by a DI framework.
Another common gotcha is that inside the constructor you don't yet have access to the HttpContext and some properties such as Request, Response, ... might not be available in the controller constructor. They become available in the Initialize method.
All this to say that I recommend you avoid putting code (other than storing ctor argument dependencies into private variables for injecting things like services, repositories, ...) in your constructor.
The Controller base class includes the ControllerContext which is a per-request context for a controller which includes references to HttpContext for example.
Let that sink in a moment.
It's very easy to write a custom ControllerBuilder or use the new DependencyResolver to serve up a singleton controller using your favorite DI container. But what that means is your controller may hold onto state from a previous request.
In fact, one of the most common bugs when people use Castle Windsor (which uses Singleton by default I've been told) to create their controllers is they get weird behavior.
As others have pointed out, if your controller is doing a lot of work in the constructor, refactor that work into a dependency on your controller which gets passed in via your controller's contstructor. Let's call that dependency a "service".
That service can itself be a singleton (as long as it doesn't hold onto per-request state) and you can use the DependencyResolver combined with your DI container to instantiate your controllers.
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