6

I'm adding some new functionality to an MVC4 site. I have just added a global static class and a global variable to hold a value in which is determined at some point during a users visit to the site and will be used as a condition later on.

The thought then occurred to me that I was unsure of just how global a static value is in this context.

Do I have to specify the global value as a session variable?

Or will each user to the site get access to it in their own session anyway and I don't have to worry about one user setting it to one value and another user having access to this set value.

Dave Alperovich
  • 31,680
  • 8
  • 71
  • 97
BenM
  • 4,110
  • 2
  • 27
  • 57
  • 4
    I cannot close-vote because of the bounty, but your question is a duplicate of [Are static class instances unique to a request or a server in ASP.NET?](http://stackoverflow.com/questions/194999/) (you really just waited two months for an answer? As it was the first web search hit for me on _"asp.net static class shared all users"_). A static class lives in an AppDomain, and an [Application Pool can serve many users from one AppDomain](http://stackoverflow.com/questions/2659571/what-is-application-pool-in-iis-and-asp-net). So yes, users _can_ share a static class. – CodeCaster Nov 08 '13 at 16:28
  • I'd actually forgotten I'd asked this as it wasn't THAT important (I used session in the end to be on the safe side) but a glance through my past questions brought this one to my attention and I realized I wanted an answer. I did search both Google and SO so I've no idea how I didn't find the duplicate, but that answers it perfectly. – BenM Nov 08 '13 at 16:36

1 Answers1

5

Your basic question: Are static globals shared among all users?

Because each MVC site is an application, all statics are shared among your app's user pool.

Deeper Question: How do I store user data for the user's entire stay?

Your question about statics will earn you sneers from some and appreciation from others. Sneers because you could look this up, appreciation because your underlying question on storing user data for easy retrieval is an important one most of us have faced.

  • You already used a session. Sessions are awkward. They expire. They're particularly unreliable when you use load balancing. To deal with expired sessions, I've used action filters; The action filter checks for null session variable OnActionExecuting, re-populating the session if it is NULL.

  • I've had more success with cookies. Cookies have their own issues. Some client browsers don't support them. But cookies are accepted more and more often. The objections become less common.

Dave Alperovich
  • 31,680
  • 8
  • 71
  • 97