5

Does more than one instance of a controller get created per App-Domain? If so under what conditions?

Joshua Enfield
  • 17,642
  • 10
  • 51
  • 98

2 Answers2

8

A new instance of a controller is created for each request by MVC, so you may end up with multiple instances running on different threads.

There is nothing stopping you from creating multiple instances yourself.

The controller should be stateless.

Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
  • So if I am a user making requests to a controller - Every request I make is to a different controller instance i.e. class fields shouldn't be used in a controller? – Joshua Enfield Jul 01 '11 at 19:45
  • It's not any different from traditional asp.net forms, each request acted on a new instance of the page. They just worked hard to hide that from you. – asawyer Jul 01 '11 at 19:48
  • @Joshua - yes you shouldn't use any fields - stateless code scales much better and is less error-prone. – Jakub Konecki Jul 01 '11 at 19:59
  • 1
    How does this work when there are multiple partial views rendered in the same request? Is the same instance of the controller resused (ie, if the Controller has a field with an instance of a WCF Proxy, will the same Proxy be resued?) – Anders Nov 13 '14 at 10:29
  • @Anders views are orthogonal to controllers. A Controller can render one partial view, or multiple partial views if they are rendered from the view itself. Rendering a partial view doesn't create a new controller. – Jakub Konecki Nov 13 '14 at 10:32
  • @JakubKonecki Sorry, I think I was a bit unclear. I meant rendering a Partial View indirectly using RenderAction() or similar. I found this question: http://stackoverflow.com/questions/1896497/like-html-renderaction-but-without-reinstantiating-the-controller-object There doesn't seem to be an answer saying if it possible in some way, rather suggestions to put everything inside the main Model, however that isn't really an answer to the actual technical question in that post. – Anders Nov 13 '14 at 10:57
2

As Jakub has said, using the default controller factory, you get one controller instance per request.

Always ensure that the controllers are stateless - in the event that your application is ever run on a web farm or, say, Windows Azure, you can't even guarantee that subsequent requests are served by the same machine.

Instead, put any data that must be preserved across requests into Session State (or use your back-end data store).

Steve Morgan
  • 12,978
  • 2
  • 40
  • 49