Create an ISession specific cache

Sometimes it is useful to create a cache specific to a particular session. I use this for pre-NH cache in my repositories that I can query with Linq before hitting NH sometimes. You could easily modify this to not be templated and instead work for any object…

If you think there is something wrong with this approach please let me know. :)

public class SessionCache<T>
    {
        private ISession sn;
        private IList<T> entities;
 
        private void ValidateSession(ISession session)
        {
            if(sn == session)
                return;
            sn = session;
            entities = new List<T>();
        }
 
        public void Add(ISession session, params T [] entity)
        {
            ValidateSession(session);
            foreach (T t in entity)
            {
                if(!Equals(t, default(T)) && !entities.Contains(t))
                    entities.Add(t);
            }
        }
 
        public void Remove(T entity, ISession session)
        {
            ValidateSession(session);
            if(entities.Contains(entity))
                entities.Remove(entity);
        }
 
        public T[] GetEntities(ISession session)
        {
            ValidateSession(session);
            return entities.ToArray();
        }
 
        public void Clear()
        {
            if(entities != null)
                entities.Clear();
        }
    }
This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>