2006-09-23

HttpContext Items Strongly Typed

I have just refactored my nHibernate session store in HttpContext.Items to use this as the base class. This fits perfectly with the spring wiring and means that i can also use it in other projects, for other items that i want strongly typed access to the object. I forgot the dispose method so i was having bad memory leaks. See also the default(T) keyword, interesting.

    public abstract class AbstractObjectCacher<T> {
        #region IoC
        private IObjectCache<T> cache;
        public IObjectCache<T> Cache {
            set { cache = value; }
            get { return cache; }
        }
        #endregion
        public T Get() {
            return cache.Get();
        }
        public void Set(T obj) {
            cache.Set(obj);
        }
        public void Dispose() {
            T obj = Get();
            if(obj != null) {
                Set(default(T));
                if(obj is IDisposable) {
                    ((IDisposable)obj).Dispose();
                }
                obj = default(T);
            }
            cache.Clear();
        }
    }

So for instance, the thread store i use for unit testing will look like this:

    public class ThreadObjectCache<T> : IObjectCache<T> {
        #region IoC
        private string key;
        public string Key {
            set {
                key = value;
                ThreadStore.Initialise(key);
            }
            get { return key; }
        }
        #endregion
        public T Get() {
            return (T)ThreadStore.Get(key);
        }
        public void Set(T obj) {
            ThreadStore.Set(key, obj);
        }
        public void Clear() {
            ThreadStore.Set(key, null);
        }
        public void Dispose() {
            ThreadStore.Dispose(key);
        }
    }

And the HttpContext store will look like this:

    public class HttpContextCache<T> : IObjectCache<T> {
        #region IoC
        private string key;
        public string Key {
            set { key = value; }
            get { return key; }
        }
        #endregion
public T Get() {
            return (T)HttpContext.Current.Items[key];
        }
        public void Set(T obj) {
            HttpContext.Current.Items[key] = obj;
        }
        public void Clear() {
            HttpContext.Current.Items[key] = null;
        }
        public void Dispose() {
            HttpContext.Current.Items.Remove(key);
        }
    }