Clear The Sitecore CustomCache After Publishing

Part 3

February 26, 2022

By Mike Payne

In our first article in the series, Part 1: How to Implement the Sitecore CustomCache that cached SOLR content search results. The problem with this cache is: how do we update the results when new items are added to the index?

Custom Cache Clearing On Publish

With our set up in Part 1, new items would not be available until the cache expires.

So lets implement a function that runs on the publish pipeline in Sitecore which clears our specified caches.


<sitecore>
	<events> 
		<event name="publish:end"> 
			<handler type="Namespace.CacheClearer, Mydll" method="ClearCaches"> 
				<caches hint="list"> 
					<cache>SearchResultsCache.SearchResults</cache> 
				</caches> 
			</handler> 
		</event> 
		<event name="publish:end:remote"> 
			<handler type="Namespace.CacheClearer, Mydll" method="ClearCaches"> 
				<caches hint="list"> 
					<cache>SearchResultsCache.SearchResults</cache> 
				</caches> 
			</handler> 
		</event> 
	</events>
</sitecore>

Here is the code that will clear out our custom cache(s) that we defined in the above XML


public class CacheClearer 
  {
    public void ClearCaches(object sender, EventArgs args)
    {
      Assert.ArgumentNotNull(sender, "sender");
      Assert.ArgumentNotNull(args, "args");
      try
      {
        DoClear();
      }
      catch (Exception ex)
      {
        Log.Error(this + ": " + ex, ex, this);
      }
    }
 
    private void DoClear()
    {
      foreach (string cacheName in Caches)
      {
        Cache cache = CacheManager.FindCacheByName(cacheName);
        if (cache == null)
          continue;
        Log.Info(this + ". Clearing " + cache.Count + " items from " + cacheName, this);
        cache.Clear();
      }
    }
 
    private readonly ArrayList _caches = new ArrayList();
    public ArrayList Caches
    {
      get
      {
        return this._caches;
      }
    }
  }

Mike Headshot

Mike Payne

Development Team Lead

Mike is a Development Team Lead who is also Sitecore 9.0 Platform Associate Developer Certified. He's a BCIS graduate from Mount Royal University and has worked with Sitecore for over seven years. He's a passionate full-stack developer that helps drive solution decisions and assist his team. Mike is big into road cycling, playing guitar, working out, and snowboarding in the winter.