5

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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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?
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.
@Joshua - yes you shouldn't use any fields - stateless code scales much better and is less error-prone.
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 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.
|
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).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.