2

We have based our implementation on Clear Sitecore cache for an item from cache programmatically to clear an item from prefetch cache as below

Cache prefetchCache = GetPrefetchCache(Database database);
prefetchCache.RemoveKeysContaining(itemID.ToString());

private Cache GetPrefetchCache(Database database)
    {
        foreach (var cache in global::Sitecore.Caching.CacheManager.GetAllCaches())
        {
            if (cache.Name.Contains(string.Format("Prefetch data({0})", database.Name)))
            {
                return cache;
            }
        }
    }  

But the Cache class of 8.2 is modified to ICacheInfo in 9.2 and RemoveKeysContaining is not available. Is there any way to remove a particular item from prefetchCache in 9.2

2 Answers 2

3

Sitecore has changed the implementation to ICacheInfo. However, you can still use the method RemoveKeysContaining on the cache once you have applied the Sitecore.Caching.Cache casting.

The ICacheInfo has multiple implementations and the class Cache is one of the implementation.

Please see below code snippet:

Cache prefetchCache = GetPrefetchCache(database);

//Check for null before applying method
if (prefetchCache != null)
{
    prefetchCache.RemoveKeysContaining(itemID.ToString());
}

private Cache GetPrefetchCache(Database database)
{
    foreach (var cache in global::Sitecore.Caching.CacheManager.GetAllCaches())
    {
        if (cache.Name.Contains(string.Format("Prefetch data({0})", database.Name)))
        {
            return cache as Cache;
        }
    }
}  

Note that the Cache is from the namespace Sitecore.Caching.Cache from assembly Sitecore.Kernel.dll

2
  • thanks Hishaam. will do the change and test.
    – PVM
    Aug 22, 2020 at 4:35
  • this worked. Thank you.
    – PVM
    Aug 27, 2020 at 3:10
1

Just an update for Sitecore 9.3 and higher:

In Sitecore 9.3 almost all of caches are generic and have types like Cache<T>. And Sitecore.Caching.CacheManager.GetAllCaches() contains a list these caches that have different class types. Almost all of them are not castable to Cache and return null on casting "cache as Cache".

So only one working that I found is:

var prefetchCache = CacheManager.FindCacheByName<ID>("SqlDataProvider - Prefetch data(" + database + ")");
if (prefetchCache != null)
{
     prefetchCache.Remove(itemId);
}

And one helpful picture "just to know" how item caching works before hitting database: enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.