Partial Sitecore Cache Clearing by Item

Sometimes you just want to clear part of the Sitecore cache and not the entire thing. Taking a page out of the Staging module philosophy, you can easily clear cache by specific items.

First, make sure you understand the basics of Sitecore cache and how requests are handled.

The example method below, clears an enumerated list of items by GUID given a database context.


public static void ClearDataItemCache(Database database, IEnumerable ids)

{

    Cache prefetchCache = GetPrefetchCache(database);

    foreach (ID id in ids)

    {

        if (!ID.IsNullOrEmpty(id))

        {

            database.Caches.ItemCache.RemoveItem(id);

            database.Caches.DataCache.RemoveItemInformation(id);

            database.Caches.StandardValuesCache.RemoveKeysContaining(id.ToString());

            if (prefetchCache != null)

            {

                prefetchCache.Remove(id);

            }

        }

    }

}

Advertisements