An example caching class for Sitecore

Previously I posted about the generalities of implementing a Cache in Sitecore using the CustomCache class. Well, I’ve actually implemented a few caches for Sitecore using this; let’s have a look at my general pattern. 

I’ve just been caching strings; although other objects can be cached, mostly all I need are strings or, sometimes a few IDs.

First, I defined my cache class:

public class MyCache : CustomCache
{
public MyCache() : base("Example.MyCache", StringUtil.ParseSizeString(Settings.GetSetting("Example.Cache.Settings.Size", "20MB")))
{
Sitecore.Events.Event.Subscribe("publish:end", this.OnPublishEnd);
Sitecore.Events.Event.Subscribe("publish:end:remote", this.OnPublishEnd);
}
protected virtual void OnPublishEnd(object sender, System.EventArgs eventArgs)
{
this.Clear();
}
new public void SetString(string key, string value)
{
base.SetString(key, value);
}
new public string GetString(string key)
{
return base.GetString(key);
}
}

And then I defined a class, using the singleton pattern, to instantiate and manage that cache.

public static class CacheManager
{
private static readonly MyCache _myCache;
static CacheManager()
{
_myCache = new MyCache();
}
public static string GetMyCache(string key)
{
return _myCache.GetString(key);
}
public static void SetMyCache(string key, string value)
{
_myCache.SetString(key, value);
}
}

And that’s it – which was all pretty painless.

Points to note:

  • You have to register your cache class to receive (and handle) publishing:end events. Otherwise it will not automatically clear when items are published. Yeah, I know, I’m not convinced I like that either; it certainly came as a surprise.
  • It does only handle strings. You can cache objects – but then you need to estimate the size of the objects, and it all starts to get a bit more complicated ( See this post ). I’m not sure I like having to use reflection just to put something into a cache…
  • You can just use the .NET cache – but then you have to do something to clear the cache on events like publishing end. Ben Golden has also described that here in his PublishingCacheDependency. I think that this is the route I’d go for caching objects, rather than simple strings; you don’t need to estimate the object size with the ASP.NET cache, and the PublishingCacheDependency

References:

Advertisements
An example caching class for Sitecore

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s