Monday, 9 March 2015

How to iterate through Microsoft Enterprise Library CacheManager?

Microsoft.Practices.EnterpriseLibrary.Caching.ICacheManager doesn't have a method / property that allow you retrieve the entire Cache items together. I had such a requirement and found a work around. This is using reflection to get "realCache" field in CacheManager and then looping through Cache.CurrentCacheState.

GetData() retrieves a single item from the Cache.

ICacheManager cacheManager = CacheFactory.GetCacheManager("cacheName");
object cacheItem = cacheManager.GetData("cacheKey");

Retrieving and iterating the entire Cache


using Microsoft.Practices.EnterpriseLibrary.Caching;

... 

string cacheName = "your-cache-name";
Cache cache;

if (TryGetCache(cacheName, out cache))
{
  foreach (DictionaryEntry cacheEntry in cache.CurrentCacheState)
  {
    object key = cacheEntry.Key;
    CacheItem cacheItem  = (CacheItem)cacheEntry.Value;
    object value = cacheItem.Value;
    Console.WriteLine("{0}: {1}", key, value)
  }
}

private static bool TryGetCache(string cacheName, out Cache cache)
{
  try
  {
    ICacheManager _cacheManager = CacheFactory.GetCacheManager(cacheName);
    cache = (Cache)_cacheManager.GetType().GetField("realCache", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(_cacheManager);
  }
  catch (Exception)
  {
    cache = null;
    return false;
  }
  return true;
}

2 comments: