-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
45473b1
commit 20ad072
Showing
1 changed file
with
67 additions
and
0 deletions.
There are no files selected for viewing
67 changes: 67 additions & 0 deletions
67
FinalProject/Core/CrossCuttingConcerns/Caching/Microsoft/MemoryCacheManager.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} | ||
} |