• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

loresoft / MediatR.CommandQuery / 12567339125

01 Jan 2025 04:52AM UTC coverage: 60.229% (-0.1%) from 60.328%
12567339125

push

github

pwelter34
switch to Testcontainers

402 of 761 branches covered (52.83%)

Branch coverage included in aggregate %.

1282 of 2035 relevant lines covered (63.0%)

19.24 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/MediatR.CommandQuery/Behaviors/DistributedCacheQueryBehavior.cs
1
using MediatR.CommandQuery.Definitions;
2

3
using Microsoft.Extensions.Caching.Distributed;
4
using Microsoft.Extensions.Logging;
5

6
namespace MediatR.CommandQuery.Behaviors;
7

8
/// <summary>
9
/// A behavior for caching the response of a query to <see cref="IDistributedCache"/>.
10
/// <typeparamref name="TRequest"/> must implement <see cref="ICacheResult"/> for the response to be cached.
11
/// </summary>
12
/// <typeparam name="TRequest">The type of the request.</typeparam>
13
/// <typeparam name="TResponse">The type of the response.</typeparam>
14
public partial class DistributedCacheQueryBehavior<TRequest, TResponse> : PipelineBehaviorBase<TRequest, TResponse>
15
    where TRequest : class, IRequest<TResponse>
16
{
17
    private readonly IDistributedCache _distributedCache;
18
    private readonly IDistributedCacheSerializer _distributedCacheSerializer;
19

20
    /// <summary>
21
    /// Initializes a new instance of the <see cref="DistributedCacheQueryBehavior{TRequest, TResponse}"/> class.
22
    /// </summary>
23
    /// <param name="loggerFactory">The logger factory.</param>
24
    /// <param name="distributedCache">The distributed cache.</param>
25
    /// <param name="distributedCacheSerializer">The distributed cache serializer.</param>
26
    /// <exception cref="System.ArgumentNullException"></exception>
27
    public DistributedCacheQueryBehavior(
28
        ILoggerFactory loggerFactory,
29
        IDistributedCache distributedCache,
30
        IDistributedCacheSerializer distributedCacheSerializer)
31
        : base(loggerFactory)
×
32
    {
33
        ArgumentNullException.ThrowIfNull(distributedCache);
×
34
        ArgumentNullException.ThrowIfNull(distributedCacheSerializer);
×
35

36
        _distributedCache = distributedCache;
×
37
        _distributedCacheSerializer = distributedCacheSerializer;
×
38
    }
×
39

40
    /// <inheritdoc />
41
    protected override async Task<TResponse> Process(
42
        TRequest request,
43
        RequestHandlerDelegate<TResponse> next,
44
        CancellationToken cancellationToken)
45
    {
46
        ArgumentNullException.ThrowIfNull(request);
×
47
        ArgumentNullException.ThrowIfNull(next);
×
48

49
        // cache only if implements interface
50
        var cacheRequest = request as ICacheResult;
×
51
        if (cacheRequest?.IsCacheable() != true)
×
52
            return await next().ConfigureAwait(false);
×
53

54
        var cacheKey = cacheRequest.GetCacheKey();
×
55

56
        // check cache
57
        var cachedBuffer = await _distributedCache
×
58
            .GetAsync(cacheKey, cancellationToken)
×
59
            .ConfigureAwait(false);
×
60

61
        if (cachedBuffer != null)
×
62
        {
63
            var cachedItem = await _distributedCacheSerializer
×
64
                .FromByteArrayAsync<TResponse>(cachedBuffer)
×
65
                .ConfigureAwait(false);
×
66

67
            LogCacheAction(Logger, "Hit", cacheKey);
×
68

69
            return cachedItem;
×
70
        }
71

72
        LogCacheAction(Logger, "Miss", cacheKey);
×
73

74
        // continue if not found in cache
75
        var result = await next().ConfigureAwait(false);
×
76
        if (result == null)
×
77
            return result;
×
78

79
        // save to cache
80
        var itemBuffer = await _distributedCacheSerializer
×
81
            .ToByteArrayAsync(result)
×
82
            .ConfigureAwait(false);
×
83

84
        var options = new DistributedCacheEntryOptions
×
85
        {
×
86
            SlidingExpiration = cacheRequest.SlidingExpiration(),
×
87
            AbsoluteExpiration = cacheRequest.AbsoluteExpiration(),
×
88

×
89
        };
×
90

91
        await _distributedCache
×
92
            .SetAsync(cacheKey, itemBuffer, options, cancellationToken)
×
93
            .ConfigureAwait(false);
×
94

95
        LogCacheAction(Logger, "Insert", cacheKey);
×
96

97
        return result;
×
98
    }
×
99

100
    [LoggerMessage(1, LogLevel.Trace, "Cache {Action}; Key: '{CacheKey}'")]
101
    static partial void LogCacheAction(ILogger logger, string action, string cacheKey);
102

103
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc