-
Notifications
You must be signed in to change notification settings - Fork 249
Expand file tree
/
Copy pathMemoryCacheDefault.cs
More file actions
95 lines (82 loc) · 2.42 KB
/
MemoryCacheDefault.cs
File metadata and controls
95 lines (82 loc) · 2.42 KB
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Threading.Tasks;
namespace WebApi.OutputCache.Core.Cache
{
public class MemoryCacheDefault : IApiOutputCache
{
private static readonly MemoryCache Cache = MemoryCache.Default;
private static void RemoveStartsWith(string key)
{
lock (Cache)
{
Cache.Remove(key);
}
}
private static T Get<T>(string key) where T : class
{
var o = Cache.Get(key) as T;
return o;
}
private static void Remove(string key)
{
lock (Cache)
{
Cache.Remove(key);
}
}
private static bool Contains(string key)
{
return Cache.Contains(key);
}
private static void Add(string key, object o, DateTimeOffset expiration, string dependsOnKey = null)
{
var cachePolicy = new CacheItemPolicy
{
AbsoluteExpiration = expiration
};
if (!string.IsNullOrWhiteSpace(dependsOnKey))
{
cachePolicy.ChangeMonitors.Add(
Cache.CreateCacheEntryChangeMonitor(new[] { dependsOnKey })
);
}
lock (Cache)
{
Cache.Add(key, o, cachePolicy);
}
}
public virtual Task<IEnumerable<string>> AllKeysAsync
{
get
{
return Task.FromResult(Cache.Select(x => x.Key));
}
}
public virtual Task RemoveStartsWithAsync(string key)
{
RemoveStartsWith(key);
return Task.FromResult(0);
}
public virtual Task<T> GetAsync<T>(string key) where T : class
{
return Task.FromResult(Get<T>(key));
}
public virtual Task RemoveAsync(string key)
{
Remove(key);
return Task.FromResult(0);
}
public virtual Task<bool> ContainsAsync(string key)
{
return Task.FromResult(Contains(key));
}
public virtual Task AddAsync(string key, object value, DateTimeOffset expiration, string dependsOnKey = null)
{
Add(key, value, expiration, dependsOnKey);
return Task.FromResult(0);
}
}
}