Create an ISession specific cache
Friday, September 26th, 2008Sometimes 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();
}
}
