-
Notifications
You must be signed in to change notification settings - Fork 0
/
MemoryCacheManager.cs
66 lines (57 loc) · 2.17 KB
/
MemoryCacheManager.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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
{
public 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);
}
}
}
}