So far I've been using Session to pass some variables from one page to another. For instance user role. When a user logs in to the web application the role id of the user is kept in Session and that role is checked at different parts of the application. I've recently started thinking why not use static members instead. I can store the same information in a static field and easily access it anywhere in my application (well anywhere the namespace in which that static field resides is included.) I know that using Session variables comes handy sometimes, such that:
- Any kind of data can be stored in Session. It then must be casted however.But static fields accept data with the correct datatype only.
- Session variables will expire after a certain time which is the behavior we need in many cases.
Apart from the above, are there any other reasons why I should not use static fields to store data and have it available everywhere?
No, using static variables for this is not the way to go:
Fundamentally, you have two choices for propagating information around your application:
If you can use load-balancing to keep all users going to the same server, and if you don't mind sessions being lost when the AppDomain is recycled1 or a server going down, you can keep it in memory, keyed by session ID... but be careful.
1 There may be mechanisms in ASP.NET to survive this, propagating session information from one AppDomain to another - I'm not sure
You forget one thing (I think)
Static data will be the same for all users of the application, while session is "per user".
So for your "User Role" scenario, I would expect funny results ;)
They are two very different things.
It's often helpful to abstract Session values with a helper class. This can improve testability and also allows you to strongly type properties and perform the cast in the internals of the class.
Example:
See also:
Static fields would be shared across all users.
In as web environment, you will have several threads running together.
Updating any static members would need proper concurrency control. Done wrong, this would slow down your site performance significantly.
Sessions can be moved out of process and shared across a web farm.
Out of proc sessions would exist even if your app server crashed.