Targetprocess Product Blog

Agile development on a real project (we do Kanban)

TargetProcess Development Tricks: Clear NHiberante cache using ASP.NET handler (.ashx)

Sometimes we need to clear cache of NHibernate. For example when the database was changed without using NHibernate. We have created the corresponding handler in web application ClearCache.ashx with the following code:

<%@ WebHandler Language="C#" Class="ClearCache" %>
using System;
using System.Collections;
using System.Web;
using NHibernate;

public class ClearCache : IHttpHandler
{
  public void ProcessRequest(HttpContext context)
  {
      context.Response.ContentType = "text/plain";

      //Need to retrieve ISession using your NHibernate session provider. In my case it is done in the following way
      ISession session = Portal.Instance.GetCurrentSession();

      DoCacheClearing(session);

      context.Response.Write("Done");
  }

  public void DoCacheClearing(ISession session)
  {
      ISessionFactory factory = session.SessionFactory;

      factory.EvictQueries();

      ICollection types = factory.GetAllClassMetadata().Keys;

      foreach (Type type in types)
          factory.Evict(type);

      foreach (string role in factory.GetAllCollectionMetadata().Keys)
          factory.EvictCollection(role);
  }

  public bool IsReusable { get { return false; } }

}

Targetprocess Help

All you want to know about Targetprocess

Recent posts