I am just wondering, is there a new controller instance for each request? How does this actually work? I read something like that after an incoming request routing selects correct controller.. and I guess it creates a new instance of that and then the controller handles the request further. If that is so, what about actions redirecting to other actions? Does that initiate new routing process and new instance of controller, too?
Thanks in advance.
A Controller is created for every request by the ControllerFactory (which by default is the DefaultControllerFactory ).
The main difference is: Web API is a service for any client, any devices, and MVC Controller only serve its client.
Using the Add Controller Menu Option The easiest way to create a new controller is to right-click the Controllers folder in the Visual Studio Solution Explorer window and select the Add, Controller menu option (see Figure 1). Selecting this menu option opens the Add Controller dialog (see Figure 2).
Controllers are essentially the central unit of your ASP.NET MVC application. It is the 1st recipient, which interacts with incoming HTTP Request. So, the controller decides which model will be selected, and then it takes the data from the model and passes the same to the respective view, after that view is rendered.
Yes, a new instance in instantiated for each request, and destroyed at the end of the request.
Each route is handled by an instance of an MvcRouteHandler. The default handler calls into the ControllerFactory, which, based on the url tokens, instantiates a new controller via a reflection call to Activator.CreateInstance().
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