/
MemoryCacheStore.cs
81 lines (71 loc) · 2.85 KB
/
MemoryCacheStore.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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System;
using System.Threading;
using System.Threading.Tasks;
using Functional.Result;
using Functional.Result.Extensions;
using Microsoft.Extensions.Caching.Memory;
using mrlldd.Caching.Exceptions;
using mrlldd.Caching.Flags;
namespace mrlldd.Caching.Stores.Internal
{
internal class MemoryCacheStore : ICacheStore<InMemory>
{
private readonly IMemoryCache memoryCache;
public MemoryCacheStore(IMemoryCache memoryCache)
{
this.memoryCache = memoryCache;
}
public Result<T> Get<T>(string key, ICacheStoreOperationMetadata metadata)
{
return Result.Of(() => memoryCache.Get<T>(key))
.Bind(t => t != null ? t : throw new CacheMissException(key));
}
public ValueTask<Result<T>> GetAsync<T>(string key, ICacheStoreOperationMetadata metadata,
CancellationToken token = default)
{
return new(Get<T>(key, metadata));
}
public Result Set<T>(string key, T value, CachingOptions options, ICacheStoreOperationMetadata metadata)
{
return Result.Of(new Action(() => memoryCache.Set(key, value, new MemoryCacheEntryOptions
{
SlidingExpiration = options.SlidingExpiration,
AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow
})));
}
public ValueTask<Result> SetAsync<T>(string key, T value, CachingOptions options,
ICacheStoreOperationMetadata metadata,
CancellationToken token = default)
{
var result = Result.Of(() =>
{
memoryCache.Set(key, value, new MemoryCacheEntryOptions
{
SlidingExpiration = options.SlidingExpiration,
AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow
});
});
return new ValueTask<Result>(result);
}
public Result Refresh(string key, ICacheStoreOperationMetadata metadata)
{
return Result.Of(new Action(() => memoryCache.Get(key)));
}
public ValueTask<Result> RefreshAsync(string key, ICacheStoreOperationMetadata metadata,
CancellationToken token = default)
{
var result = Result.Of(new Action(() => memoryCache.Get(key)));
return new ValueTask<Result>(result);
}
public Result Remove(string key, ICacheStoreOperationMetadata metadata)
{
return Result.Of(() => memoryCache.Remove(key));
}
public ValueTask<Result> RemoveAsync(string key, ICacheStoreOperationMetadata metadata,
CancellationToken token = default)
{
var result = Result.Of(() => { memoryCache.Remove(key); });
return new ValueTask<Result>(result);
}
}
}