Wednesday, September 06, 2006

Generic HttpContext Singleton 

Joel Ross has an interesting post about implementing the singleton pattern for objects used during the lifecycle of a web request.

This got me thinking about the Generic singleton implementation that I have used before. I wondered if you could combine the two to make a Generic HttpContext singleton. Here is my first attempt. I think it should work, but I have not tried it.

I guess the key is the "key". It may be better to use the fully qualified class name for the key instead of just using the generic type's name. It may also make sense to add a "Singleton_" prefix to the name to give it a namespace within the HttpContext.


    1 using System;

    2 using System.Collections.Generic;

    3 using System.Web;

    4 using System.Runtime.Serialization;

    5 

    6 namespace jedatu

    7 {

    8     public class ContextSingleton<T> where T : ISerializable, new()

    9     {

   10         protected ContextSingleton() { }

   11 

   12         public static T Instance

   13         {

   14             get { return Factory.Current.Instance; }

   15         }

   16 

   17         private class Factory

   18         {

   19             static Factory() { }

   20 

   21             internal static Factory Current = new Factory();

   22 

   23             internal static readonly T _instance = new T();

   24 

   25             internal T Instance

   26             {

   27                 get

   28                 {

   29                     if (HttpContext.Current == null) { return null; }

   30                     if (HttpContext.Current.Items[_instance.GetType().Name] == null)

   31                     {

   32                         HttpContext.Current.Items[_instance.GetType().Name] = _instance;

   33                     }

   34                     return (T)HttpContext.Current.Items[_instance.GetType().Name];

   35                 }

   36             }

   37         }

   38     }

   39 }


This page is powered by Blogger. Isn't yours?