Home >

Generic HttpContext Singleton

6. September 2006

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.

using System;
using System.Collections.Generic;
using System.Web;
using System.Runtime.Serialization;

namespace jedatu
{
    public class ContextSingleton where T : ISerializable, new()
    {
        protected ContextSingleton() { }

        public static T Instance
        {
            get { return Factory.Current.Instance; }
        }

        private class Factory
        {
            static Factory() { }

            internal static Factory Current = new Factory();

            internal static readonly T _instance = new T();

            internal T Instance
            {
                get
                {
                    if (HttpContext.Current == null) { return null; }
                    if (HttpContext.Current.Items[_instance.GetType().Name] == null)
                    {
                        HttpContext.Current.Items[_instance.GetType().Name] = _instance;
                    }
                    return (T)HttpContext.Current.Items[_instance.GetType().Name];
                }
            }
        }
    }
}

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading