PrimeDigit – A Design Blog by Will Shaver

September 26, 2008

Create an ISession specific cache

Filed under: Uncategorized — Will @ 5:11 pm

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();
        }
    }

1 Comment »

  1. Hello Will,

    I am very sure that this is off-topic but I would like to ask you some help regarding the accordion 2.0. For some reason I am not able to make it load with all the tabs closed and this is really annoying. Please give me a reply to my email and show you the page where I am trying that and maybe you can help me.

    Best regards,
    Alex Panait

    Comment by Alex Panait — October 10, 2008 @ 4:07 am

RSS feed for comments on this post. TrackBack URL

Leave a comment

Powered by WordPress