Invalidate the cache for a specific page in EPiServer

Cache dependencies are useful when you're caching data and want you want that data to be refreshed when a page changes, i.e. when it is published. However, sometimes you want invalidate the EPiServer cache manually for a page.

  • Ted Nyberg
  • 31 January 2013
  • 0

Background

I have a class that helps me with loading blog posts. These posts are fetched as pages and then stored into the runtime cache object, for easy access and manipulation.

Although each time a blog post is saved, I naturally have to update the cache. Since I have a couple of layers of cache dependant on the type of questionm such as; “all blog posts”, posts related to a tag, posts related to a single author. It resulted in me being forced to update quite a few cache keys. This is where the CacheDependency is so useful.

Creating a cache dependency

So first of all I created my CacheDependency object. In EPiServer.DataFactoryCache this is related to a ContentReference (in EPiServer CMS 7). So I created my dependency based on the start page reference:

private CacheDependency Dependency { get { return DataFactoryCache.CreateDependency(ContentReference.StartPage); } }

After fetching the posts I add them to the runtime cache:

CacheManager.RuntimeCacheAdd("AllPosts" + reference.ID + languageContext.SelectedLanguage, allBlogPosts, Dependency, DateTime.Now.AddHours(6), TimeSpan.Zero, CacheItemPriority.High);		

Now to updating or triggering the CacheDependency object. I first started looking at the object itself that have quite a few properties and one method, Dispose(). This was the first thing I tried, but it didn’t work..

Invalidate the cache for a specific EPiServer page

So I had to find another way of triggering the Dependency. It might be possible to republish the start page, not sure, but I don’t want to be forced to do that each time a post is being published. So instead I found this method:

DataFactoryCache.RemovePage(ContentReference.StartPage);

This does remove the start page from the cache, but do not trigger any republish or such, just forcing the application to get it from the database again and then triggers the dependency.