0

This might be easy question, but why mvc framework create separate controller class object for each request?

I know we can change this behavior using custom controller factory, refer any of below articles (lots of other articles are available).

custom-controller-factory or custom-controller-factory-1

So my question is, if we can preserve controller object for next or subsequent request. like below code.

 //dicControllers : collection of controllers

    if(dicControllers.ContainsKey("ctrl_name")) {
       return dicControllers["ctrl_name"];
    }
    else
    {
    //create controller object 
    dicControllers["ctrl_name"] = ctrlObj;
    }

....

THEN

Why framework does not provide this functionality. Is there any certain reason?

Will it improve the application performance (Please consider object creation time)?

Is there any problem, if i will do like this?

Manoj Verma
  • 364
  • 5
  • 12
  • 2
    This might give you some hints https://stackoverflow.com/questions/13200152/why-say-that-http-is-a-stateless-protocol – Jasen Jan 22 '18 at 19:08
  • 1
    "why mvc framework create separate controller class object for each request?" essentially because every time you make a request it's a separate execution of the program. It runs your whole code from startup to end, as if it had never run before. That in turn is because HTTP is stateless. See the link provided by Jasen above. – ADyson Jan 22 '18 at 20:07
  • 1
    @ADyson - The startup code is not run on every request, but I agree that the rest of your comment makes total sense. There is no point in trying to "preserve a controller instance across requests" as these instances are cheap to create and each request will provide different runtime values of `HttpContext`. – NightOwl888 Jan 23 '18 at 08:12
  • @NightOwl888 Yes that's a useful clarification, thanks - the application start event only runs when the site is first started in the webserver, but most other stuff gets executed every time. https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/lifecycle-of-an-aspnet-mvc-5-application explains the lifecycle in more detail, the OP might find this of interest. – ADyson Jan 23 '18 at 09:27

0 Answers0