-
-
Notifications
You must be signed in to change notification settings - Fork 92
Expand file tree
/
Copy pathCachedRepository.cs
More file actions
69 lines (56 loc) · 2.37 KB
/
CachedRepository.cs
File metadata and controls
69 lines (56 loc) · 2.37 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
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Threading.Tasks;
using LinkDotNet.Blog.Domain;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace LinkDotNet.Blog.Infrastructure.Persistence;
public sealed class CachedRepository<T> : IRepository<T>
where T : Entity
{
private readonly IRepository<T> repository;
private readonly IMemoryCache memoryCache;
public CachedRepository(IRepository<T> repository, IMemoryCache memoryCache)
{
this.repository = repository;
this.memoryCache = memoryCache;
}
public ValueTask<HealthCheckResult> PerformHealthCheckAsync() => repository.PerformHealthCheckAsync();
public async ValueTask<T?> GetByIdAsync(string id) =>
(await memoryCache.GetOrCreateAsync(id, async entry =>
{
entry.SlidingExpiration = TimeSpan.FromDays(7);
return await repository.GetByIdAsync(id);
}))!;
public async ValueTask<IPagedList<T>> GetAllAsync(Expression<Func<T, bool>>? filter = null,
Expression<Func<T, object>>? orderBy = null,
bool descending = true,
int page = 1,
int pageSize = int.MaxValue) =>
await repository.GetAllAsync(filter, orderBy, descending, page, pageSize);
public async ValueTask<IPagedList<TProjection>> GetAllByProjectionAsync<TProjection>(
Expression<Func<T, TProjection>> selector,
Expression<Func<T, bool>>? filter = null,
Expression<Func<T, object>>? orderBy = null,
bool descending = true,
int page = 1,
int pageSize = int.MaxValue) =>
await repository.GetAllByProjectionAsync(selector, filter, orderBy, descending, page, pageSize);
public async ValueTask StoreAsync(T entity)
{
ArgumentNullException.ThrowIfNull(entity);
await repository.StoreAsync(entity);
if (!string.IsNullOrEmpty(entity.Id))
{
memoryCache.Remove(entity.Id);
}
}
public async ValueTask DeleteAsync(string id)
{
await repository.DeleteAsync(id);
memoryCache.Remove(id);
}
public async ValueTask DeleteBulkAsync(IReadOnlyCollection<string> ids) => await repository.DeleteBulkAsync(ids);
public async ValueTask StoreBulkAsync(IReadOnlyCollection<T> records) => await repository.StoreBulkAsync(records);
}