Skip to content

Commit

Permalink
add CacheManager
Browse files Browse the repository at this point in the history
  • Loading branch information
yasemingerboga committed Mar 12, 2021
1 parent 45473b1 commit 20ad072
Showing 1 changed file with 67 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
using Core.Utilities.IoC;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using System.Text.RegularExpressions;
using System.Linq;

namespace Core.CrossCuttingConcerns.Caching.Microsoft
{
class MemoryCacheManager : ICacheManager
{
//Adapter Pattern
IMemoryCache _memoryCache;
public MemoryCacheManager()
{
_memoryCache = ServiceTool.ServiceProvider.GetService<IMemoryCache>();
}
public void Add(string key, object value, int duration)
{
_memoryCache.Set(key, value, TimeSpan.FromMinutes(duration));
}

public T Get<T>(string key)
{
return _memoryCache.Get<T>(key);
}

public object Get(string key)
{
return _memoryCache.Get(key);
}

public bool IsAdd(string key)
{
return _memoryCache.TryGetValue(key,out _);
}

public void Remove(string key)
{
_memoryCache.Remove(key);
}

public void RemoveByPattern(string pattern)
{
var cacheEntriesCollectionDefinition = typeof(MemoryCache).GetProperty("EntriesCollection", System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Instance);
var cacheEntriesCollection = cacheEntriesCollectionDefinition.GetValue(_memoryCache) as dynamic;
List<ICacheEntry> cacheCollectionValues = new List<ICacheEntry>();

foreach (var cacheItem in cacheEntriesCollection)
{
ICacheEntry cacheItemValue = cacheItem.GetType().GetProperty("Value").GetValue(cacheItem, null);
cacheCollectionValues.Add(cacheItemValue);
}

var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
var keysToRemove = cacheCollectionValues.Where(d => regex.IsMatch(d.Key.ToString())).Select(d => d.Key).ToList();

foreach (var key in keysToRemove)
{
_memoryCache.Remove(key);
}
}
}
}

0 comments on commit 20ad072

Please sign in to comment.