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.
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.
精彩评论