0

I have three action methods and public field public int idUser:

public class HomeController : Controller
{   
    //public field 
    public int idUser = 0; 

    public ActionResult Index()
    {   
        string userLogin = User.Identity.Name;                        
        using (SmoothEntities db = new SmoothEntities())
        {                
            idUser = (db.Users.Where(c => c.Name == userLogin).First()).ID_User;
            return View(db.Employees.Where(u => u.ID_User == idUser).ToList());
        }  
    }
    public ActionResult About()
    {
        string userLogin = User.Identity.Name;            
        int idUser = 0;
        using (SmoothEntities db = new SmoothEntities())
        {                
            idUser = (db.Users.Where(c => c.Name == userLogin).First()).ID_User;
            return View(db.Employees.Where(u => u.ID_User == idUser).ToList());
        }  
    }

    public ActionResult Contact()
    {            
        return View();
    }
}

Let us imagine that Bob and Bill have logged simultaneously on to the web site. Am I right that Bob and Bill will have two different values of the public field idUser if Bob will execute public ActionResult Index() and Bill will execute public ActionResult About()?

Why do I use public field? As I do not want always access data from server in Action methods, I think it will decrease performance of my web site, so I have decided to create public field.

StepUp
  • 36,391
  • 15
  • 88
  • 148
  • Global variables are bad practise! Use Web-Caching or a Session in order to preserve the user id! For example you will take the UserId on logon, so store it there and use it in the controller again, no need to waste time and resources asking for it again. – keenthinker Jan 04 '15 at 10:12
  • _"I think it will decrease performance of my web site"_ - using a class level variable instead of a local variable isn't going to have any noticeable performance impact. – CodeCaster Jan 04 '15 at 10:16

2 Answers2

1

Am I right that Bob and Bill will have two different values of the public field idUser if Bob will execute public ActionResult Index() and Bill will execute public ActionResult About()?

Yes, you're right (even if they execute the same method).

By default, for every request that hits the asp.net mvc, the asp.net mvc will create a new instance of the controller to service the request so that they don't share the field values.

Khanh TO
  • 48,509
  • 13
  • 99
  • 115
1

Regardless of wether it is a good idea or not, yes, each request will have a different instance of the controller class, and so the same goes to the field. You can override this behavior by implementing a controller builder that somehow caches and returns the same controller instance to all/some requests. If you just want your field to be shared, make it static.

Ricardo Peres
  • 13,724
  • 5
  • 57
  • 74