Pete
Pete

Reputation: 1810

Are ASP.NET controllers guaranteed to be used only once per request?

If we want to create some objects to be used by all action methods in a controller, can we store them as instance variables in the controller?

Phil Haack mentions that controllers are not meant to be reused in this old post: Asp.Net MVC Beta: Previous RouteData overrides current RouteData?

But is this one-controller-per-request behavior guaranteed?

I don't want to be in a situation where a reused controller has data from another request.

Upvotes: 3

Views: 1452

Answers (3)

Gregoire
Gregoire

Reputation: 24872

You can use TempData to store temporary data in your controller

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532605

Yes (to the question in your title) and No (to the question in your post).

A new controller instance is created for each request. You might be able to do this by using your own controller factory that caches controllers and only creates them as needed, but I wouldn't recommend it. You'd be better off to simply cache any information that is needed either in the Session or the Cache or store the information in the View (hidden, if necessary) than to go to the trouble of creating a new controller factory.

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1039298

Every time you call an action method, a new instance of the controller class should be created. So it is not a good idea to have your action methods depend on instance variables. If you use the DefaultControllerFactory then you will get a new controller instance for each request. If you use a custom controller factory you could override this behavior, which I wouldn't recommend.

Upvotes: 1

Related Questions