1
1
using System ;
2
2
using System . Linq . Expressions ;
3
- using System . Threading ;
4
3
using System . Threading . Tasks ;
5
4
using LinkDotNet . Blog . Domain ;
6
5
using Microsoft . Extensions . Caching . Memory ;
7
- using Microsoft . Extensions . Primitives ;
8
6
9
7
namespace LinkDotNet . Blog . Infrastructure . Persistence ;
10
8
11
- public sealed class CachedRepository < T > : IRepository < T > , IDisposable
9
+ public sealed class CachedRepository < T > : IRepository < T >
12
10
where T : Entity
13
11
{
14
12
private readonly IRepository < T > repository ;
15
13
private readonly IMemoryCache memoryCache ;
16
- private CancellationTokenSource resetToken = new ( ) ;
17
14
18
15
public CachedRepository ( IRepository < T > repository , IMemoryCache memoryCache )
19
16
{
20
17
this . repository = repository ;
21
18
this . memoryCache = memoryCache ;
22
19
}
23
20
24
- private MemoryCacheEntryOptions Options => new ( )
25
- {
26
- ExpirationTokens = { new CancellationChangeToken ( resetToken . Token ) } ,
27
- AbsoluteExpirationRelativeToNow = TimeSpan . FromDays ( 7 ) ,
28
- } ;
29
-
30
21
public async ValueTask < T > GetByIdAsync ( string id )
31
22
{
32
- if ( ! memoryCache . TryGetValue ( id , out T value ) )
23
+ return await memoryCache . GetOrCreateAsync ( id , async entry =>
33
24
{
34
- value = await repository . GetByIdAsync ( id ) ;
35
- memoryCache . Set ( id , value , Options ) ;
36
- }
37
-
38
- return value ;
25
+ entry . AbsoluteExpirationRelativeToNow = TimeSpan . FromDays ( 7 ) ;
26
+ return await repository . GetByIdAsync ( id ) ;
27
+ } ) ;
39
28
}
40
29
41
30
public async ValueTask < IPagedList < T > > GetAllAsync (
@@ -58,26 +47,12 @@ public async ValueTask<IPagedList<TProjection>> GetAllByProjectionAsync<TProject
58
47
public async ValueTask StoreAsync ( T entity )
59
48
{
60
49
await repository . StoreAsync ( entity ) ;
61
- ResetCache ( ) ;
62
- memoryCache . Set ( entity . Id , entity , Options ) ;
50
+ memoryCache . Remove ( entity . Id ) ;
63
51
}
64
52
65
53
public async ValueTask DeleteAsync ( string id )
66
54
{
67
- ResetCache ( ) ;
68
55
await repository . DeleteAsync ( id ) ;
69
- }
70
-
71
- public void Dispose ( ) => resetToken ? . Dispose ( ) ;
72
-
73
- private void ResetCache ( )
74
- {
75
- if ( resetToken is { IsCancellationRequested : false , Token . CanBeCanceled : true } )
76
- {
77
- resetToken . Cancel ( ) ;
78
- resetToken . Dispose ( ) ;
79
- }
80
-
81
- resetToken = new CancellationTokenSource ( ) ;
56
+ memoryCache . Remove ( id ) ;
82
57
}
83
58
}
0 commit comments