Using HttpContext.Current.Items Effectively

posted on 11/07/07 at 12:13:54 am by Joel Ross

I'm a huge fan of HttpContext.Current.Items, and have been for a while, but I rarely see others using it. I have mixed feelings about that - am I off-base in using it and don't realize it, or did I stumble onto a gem that just isn't used as much as it could be?

I'm starting to lean towards the latter, especially after seeing this post by Mike Duncan about how he uses it. He's got a couple of great ideas that could be implemented fairly quickly. He lists out three main uses:

  • Preparing common objects early so they're available to the page
  • Making parameters and pages more testable.
  • Populating dynamic user controls easier

I've primarily used it for the first option. For example, over at Tourneytopia, we store the current pool you're looking at in a context wrapper (so it's strongly-typed). It's used on just about every page / control, and we lazy load it - so while Mike mentions populating the context with an HttpModule, we only load it the first time it's actually accessed:

   1:  public Pool Pool
   2:  {
   3:      get
   4:      {
   5:          if (HttpContext.Current.Items[Constants.ContextItems.Pool] == null)
   6:          {
   7:              Pool pool = Pool.GetPool(this.PoolId);
   8:              if (pool == null)
   9:              {
  10:                  return null;
  11:              }
  12:              else
  13:              {
  14:                  HttpContext.Current.Items[Constants.ContextItems.Pool] = pool;
  15:              }
  16:          }
  17:          return (Pool)HttpContext.Current.Items[Constants.ContextItems.Pool];
  18:      }
  19:  }


That way if it's not used at all, it never gets loaded.

His other two suggestions are interesting as well. Being able to have an alternative way to populate typically "webby" data, such as query strings, is something that's always been difficult to figure out. By using a context wrapper that's based on an interface, you can inject your own implementation into it, so you can substitute a "windowish" implementation for unit testing.

I haven't found a situation where I'm adding a lot of dynamic user controls, but any time you can get rid of calls to FindControl(), it's a good day!

Categories: Development, C#