Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are asp.net mvc 2 controllers instantiated?

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.

like image 707
MushinNoShin Avatar asked Oct 21 '10 19:10

MushinNoShin


People also ask

Can you have more than one controller in MVC?

In Spring MVC, we can create multiple controllers at a time. It is required to map each controller class with @Controller annotation.

Can two different Controllers access a single view in MVC?

Yes. Mention the view full path in the View method. If the name of your Views are same in both the controllers, You can keep the Common view under the Views/Shared directory and simply call the View method without any parameter. The View name should be same as the Action method name.

How does the controller in MVC work?

A controller is responsible for controlling the way that a user interacts with an MVC application. A controller contains the flow control logic for an ASP.NET MVC application. A controller determines what response to send back to a user when a user makes a browser request.

How controller is implemented in MVC?

In Solution Explorer, right-click the Controllers folder and then click Add, then Controller. In the Add Scaffold dialog box, click MVC 5 Controller - Empty, and then click Add. Name your new controller "HelloWorldController" and click Add.


1 Answers

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.

like image 96
Russ Cam Avatar answered Sep 20 '22 03:09

Russ Cam