24

I am writing a user authentication class. During the request there are a lot of references to the current user, so I would like to cache it in memory instead of calling the database ala singleton. I am thinking about using session and clearing it at the end of every request.

like:

 public static User Current() {
     if (Session["current-user"] == null) {
          Session["current-user"] = GetUserFromDB(); // example function, not real
     }
     return (User)Session["current-user"];

then in app_end request:

     Session.Clear();
Shawn
  • 19,465
  • 20
  • 98
  • 152

2 Answers2

40
HttpContext.Items["user"] = user;

You can reference the context items during the entire request and it will be cleaned up at the end of it.

Teun D
  • 5,045
  • 1
  • 34
  • 44
11

Use the HttpContext class. You can get to it either in the context of a controller of HttpContext.Current.

The HttpContext.Items collection is what you want to use.

Francois
  • 10,730
  • 7
  • 47
  • 80
Chad Moran
  • 12,834
  • 2
  • 50
  • 72