views:

49

answers:

1

When an asp.net application is notified of a URL, it routes it to the appropriate controller and specifically to the appropriate method.

Are those controllers placed upon the stack once? Or do they get instantiated again for each request?

For example, say I have a controller with a linq-to-sql class that gets instantiated in the declaration of the class. If I have n requests that route into that controller, have I spawned n different linq-to-sql class objects, each in their own instance of controller or just 1?

My gut tells me controllers are spawned one per request for thread safety reasons but I can't seem to dig up a better guide than my own gastrointestinal oracle.

+4  A: 

They get instantiated each time by DefaultControllerFactory by default. Specifically, in GetControllerInstance,

(IController)Activator.CreateInstance(controllerType);

CreateController is first called which calls GetControllerType to get the controller type based on the controller name and the Namespaces passed in the route data tokens. Then it calls GetControllerInstance which creates an instance of the controller.

There's no better guide than the MVC framework source code itself.

You can define your own ControllerFactory by implementing IControllerFactory and then control how and when controllers are instantiated.

Russ Cam
Thanks. Is this detailed somewhere on the msdn? I seem to have a 50/50 shot when it comes to answering my own questions with it.
MushinNoShin
Have updated with a link to the source code. It is invaluable for the curious amongst us :)
Russ Cam
Having the source code to look over is one thing but if you following the following guide to set up the Source Server you can step through the code as it goes which gives a really good idea of how it works http://weblogs.asp.net/gunnarpeipman/archive/2010/07/04/stepping-into-asp-net-mvc-source-code-with-visual-studio-debugger.aspx
Chao
@Chao- agreed :)
Russ Cam
Woooow! This is a great idea! Thank you so much, the both of you. Stackoverflow has let me improve my methods a great deal because of people like you guys. <3++;
MushinNoShin