tags:

views:

47

answers:

3

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: http://stackoverflow.com/questions/222300/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.

+1  A: 

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.

Darin Dimitrov
+3  A: 

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.

tvanfosson
To clarify, I'm trying to understand the best way to create some data to be shared by many action methods in one place. I was trying to figure out the best way to pass data from OnActionExecuting into action methods. I didn't realize that we could populate ViewData on controllerContext, which seems like it makes more sense than instance variables inside the controller. I think my question is answered: Yes, only one controller per request.
Pete
A: 

You can use TempData to store temporary data in your controller

Gregoire
Doesn't TempData live until the subsequent request too?
Pete
yes and it fills its needs, so no need to down vote it
Gregoire
The OP explicitly specified I quote: `I don't want to be in a situation where a reused controller has data from another request.`. Using TempData will do just that: reuse data from previous request.
Darin Dimitrov
No the tempdata will live across actions only for the current request...
Gregoire
When you say `actions` this means multiple requests (request per action), maybe you mean for the `current session/user`.
Darin Dimitrov
I will remove the negative vote though from your answer because the OP didn't actually specify if he meant different requests or different requests from the same user.
Darin Dimitrov
what I wanted to mean is that the data in tempData persist if in a request to a specific action there is a RedirectToAction method. After that yes, perhaps I was wrong.
Gregoire