I have to do the following, when a class is instantiated I need to store that instance by user . Since I’m working in asp.net, I was wondering if I should use some of the ways asp.net provides to persist data between user requests. (Cache cant be because the data needs to be persistent and application state cant be because it needs to be specific to an user) or if I should look a way to store that info inside the class. And it needs to be persisted until I programatically say so
Share
Session is the perfect place to store specific user data.
Let’s assume for this answer, your class that needs to be persisted across a user session is called
UserInfo. The first thing is to make sure it is marked as Serializable, so that it can be stored in Session:From code-behind or classes within the ASP.NET application’s App_Code folder, you can call session directly:
If in a class library / external assembly that is part of the application, referenced by the ASP.NET website /application, you can access session via
HttpContext.Current.Session. Your code otherwise would be very similar:When coding your class library, it’s recommended to ensure
HttpContext.Currentis not null prior to trying to access it andSession, as under certain circumstances it could be null.All of the above should meet your needs. Session by design is scoped at the user/session level so you can use the same Session key in your code. No other special requirements are needed to protect the class instance from other users/sessions. The
Cacheobject you mentioned is not the right way to go, as it is application wide, and would require you to implement your own user-level scope to ensureUserInfoinstances aren’t accidentally shared across different sessions.One last suggestion – you could even create a static utility/helper class which would access this information as needed, so that your code would not continually have to deal with the Session object. Quick example:
Using the above static class, you can now easily access the instance of the class, using
UserInfoManager.UserInformation, etc.I hope this helps.
EDIT:
One further suggestion. In our applications when we have to store a class instance per user like you do, we create a base
Pageclass, which allows direct access to the class instance via a property. This may also help you keep things well refined:Then in each code-behind in the asp.net website or web application:
As you can see, very little code is needed now to be able to access the class instance.