Sitecore 9 Caching – Sitecore.Caching.CacheManager.GetAllCaches() changed from Sitecore 8

With the increased use of dependency injection, in Sitecore, some classes do no longer return concrete classes, but interfaces instead. You therefore need to change your code, if you use the Sitecore.Caching.CacheManager. The Sitecore.Caching.Cache class is retired and have been replaced with Sitecore.Caching.ICacheInfo.

GET A LIST OF ALL CACHES:

// Get all caches, Sitecore 8
IEnumerable<Sitecore.Caching.Cache> Caches
{
  get
  {
    return CacheManager.GetAllCaches().OrderBy(c => c.Name);
  }
}


// Get all caches, Sitecore 9
IEnumerable<Sitecore.Caching.ICacheInfo> Caches
{
  get
  {
    return CacheManager.GetAllCaches().OrderBy(c => c.Name);
  }
}

CLEAR ONE CACHE ONLY:

If you wish to clear one cache only, you can no longer call Sitecore.Caching.CacheManager.FindCacheByName(cacheName), as this method is deprecated, and will result in an exception being thrown:

Unable to cast object of type ‘Sitecore.Caching.Generics.Cache`1[Sitecore.Caching.AccessResultCacheKey]’ to type ‘Sitecore.Caching.Generics.ICache`1[System.String]’.

Instead, iterate the GetAllCaches() collection and find the cache to clear:

// Calling the method from above to find a ICacheInfo object,
// then call the Clear() method
var cache = Caches.SingleOrDefault(c => c.Name == cacheName);
cache.Clear();

MORE TO READ:

Advertisements

About briancaos

Developer at Pentia A/S since 2003. Have developed Web Applications using Sitecore Since Sitecore 4.1.
This entry was posted in Sitecore 8, Sitecore 9 and tagged , , . Bookmark the permalink.

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 )

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.