Skip to content

Instantly share code, notes, and snippets.

@KarateJB
Created February 14, 2020 06:57
Show Gist options
  • Save KarateJB/4ca1e090a3481fdf95fdaea2d3506a4a to your computer and use it in GitHub Desktop.
Save KarateJB/4ca1e090a3481fdf95fdaea2d3506a4a to your computer and use it in GitHub Desktop.
[.NET Core] Get all entries from MemoryCache
/// <summary>
/// Get all CacheEnries in MemoryCache
/// </summary>
/// <param name="cache">IMemoryCache</param>
/// <returns>List of CacheEntry</returns>
public static IList<ICacheEntry> GetAllCacheEntries(this IMemoryCache cache)
{
// CacheEtries
var cacheEntries = new List<ICacheEntry>();
var field = typeof(MemoryCache).GetProperty("EntriesCollection", BindingFlags.NonPublic | BindingFlags.Instance);
var cacheEntriesCollection = field.GetValue(cache) as dynamic;
if (cacheEntriesCollection != null)
{
foreach (var cacheItem in cacheEntriesCollection)
{
// Get the "Value" from the key/value pair which contains the cache entry
ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null);
// Add the cache entry to the list
cacheEntries.Add(cacheItemValue);
}
}
return cacheEntries;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment