I have a class called UserContext that tracks the activities of a given user on my website. It should be a singleton class (just one instance per user). In a Windows Forms application, I’d could write something like this:
Class UserContext
Public Shared Current As New UserContext()
Private Sub New(appName As String)
[...]
End Class
But on an ASP.net app, this would get shared across all current users.
If this class were only being used within a Page entity I could just store the UserContext instance in a Page variable—it doesn’t necessarily need to survive postbacks. But other entities (that don’t know about Page) also call UserContext, and I’d like them all to be given the same instance.
What can I do to ensure that a class is only instantiated once per http request (or per user)? Could I use the cache for this?
Public Shared Function GetContext() As UserContext
If HttpContext.Current.Cache("CurrentUserContext") Is Nothing Then HttpContext.Current.Cache("CurrentUserContext") = New UserContext()
Return HttpContext.Current.Cache("CurrentUserContext")
End Function
Might session state be a better option?
Cache and session state both survive postbacks—is there another option that resets with each new request?
Thanks for your help!
HttpContext.Current.Cachewill be shared among all users.HttpContext.Current.Sessionis per user but persists for subsequent requests.You need
HttpContext.Current.Items:This will ensure a safe per request and per user cache store.