Quantcast
Channel: Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 285

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

$
0
0

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:


Viewing all articles
Browse latest Browse all 285

Trending Articles