简体   繁体   中英

What conforming standards is this code violating?

What is wrong with having a private ViewModel object, so that all my controller actions have access to it?

  • I'm using EF4,MVC3,DBContext, DBsets.

     public class MyController { private MyViewModel _myViewModel; public ActionResult Index(MyViewModel myViewModel){ <-- There is a model Binder making this work _myViewModel = myViewModel; return _myViewModel; } } 

Because everytime you call a controller action you get a different instance of the controller. So anything that you might have stored in instance fields of this controller from a previous action would be lost on subsequent actions. That's the reason why in ASP.NET MVC you have notions such as Session, Application State, TempData, Cookies, Cache, ... you name it.

For one thing, by making the ViewModel a member of your controller, you really limit what you can do in a multi-threaded environment. If more than 1 of your Actions is invoked on the same controller, you may end up with a race condition to determine which of the passed-in view models is used for each view.

Edit: You get a different instance of the controller each time, so this will not happen. However, it is still something to keep in mind for other classes that use private members

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM