Sitecore’s CustomCache – A simple implementation

by Max Slabyak

Sitecore comes stocked with a custom caching mechanism in its Sitecore.Caching namespace. Unfortunately, there is not much documentation on it, but this post will hopefully shed some light on this mysterious, yet useful object known as CustomCache.

To implement, you will need 3 things:

  1. Your own CustomCache class
  2. A CacheManager class
  3. The code that will be using the cache

Your own Custom Cache class

Because Sitecore.Caching.CustomCache is an abstract class, you cannot directly instantiate it, but you can inherit from it.


namespace Sitecore.Custom
{
    public class MyCustomCache : Caching.CustomCache
    {
        public MyCustomCache(string name, long maxSize) : base(name, maxSize)
        {

        }

        new public void SetString(string key, string value)
        {
            base.SetString(key, value);
        }

        new public string GetString(string key)
        {
            return base.GetString(key);
        }
    }
}

Cache Manager

You will need a static Cache Manager to “manage” your CustomCache. This manager will instantiate the CustomCache object in the constructor. This is where you will give it the name and the size – both of which will show up in under /sitecore/admin/cache.aspx which you will be able to clear.


namespace Sitecore.Custom
{
    public static class CacheManager
    {
        private static readonly MyCustomCache Cache;

        static CacheManager()
        {
            Cache = new MyCustomCache("MyCustomCache",
                     StringUtil.ParseSizeString("10KB"));
        }

        public static string GetCache(string key)
        {
            return Cache.GetString(key);
        }

        public static void SetCache(string key,string value)
        {
            Cache.SetString(key, value);
        }
    }
}

Your code that calls it

You can use the code below to set and get your cached values.


CacheManager.SetCache("myData","myDataValue");
string myData = CacheManager.GetCache("myData");

So why use this as opposed to the .NET cache out of the box? For me, it’s the simple convenience of having it clear anytime I do a Sitecore publish operation.

That’s all there is to it.

Share

One thought on “Sitecore’s CustomCache – A simple implementation

Leave a Reply

Your email address will not be published. Required fields are marked *