Reputation: 1810
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
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
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