Sitecore vary output cache by context item and datasource

Sitecore’s output cache is an excellent solution to improve the performance of a Sitecore solution. The output cache can be configured to be different for a variety of criteria as explained by John West in this post.

The most common option is the VaryByData option. I don’t think this option is documented very well, but it will vary the cache based on the datasource if it is set. The context item will be used instead if no datasource is set.

VaryByData will vary the cache based on Datasource if set, otherwise it will use the context item.

This will work well in most cases, but there are valid scenarios where the cache should vary based on the datasource and the context item. This can be avoided by adding below pipeline. This will use Sitecore’s logic to determine the cachekey, but will add the item path. The if statement can be adjusted depending on the need. Examples include setting it to the ID of the rendering that requires it or checking if rendering’s Datasource property is set if this is required for all renderings that have a datasource.

public class GenerateCacheKeyCustomized : GenerateCacheKey
{
    protected override string GenerateKey(Rendering rendering, RenderRenderingArgs args)
    {
        var cacheKey = base.GenerateKey(rendering, args);

        if (rendering.RenderingItemPath == "<your ID>")
        {
            cacheKey += string.Format("_{0}", Sitecore.Context.Item.Paths.Path);
        }

        return cacheKey;
    }
}