-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathHttpUserAgentParserMemoryCachedProvider.cs
58 lines (44 loc) · 1.97 KB
/
HttpUserAgentParserMemoryCachedProvider.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
// Copyright © https://myCSharp.de - all rights reserved
using Microsoft.Extensions.Caching.Memory;
using MyCSharp.HttpUserAgentParser.Providers;
namespace MyCSharp.HttpUserAgentParser.MemoryCache;
/// <inheritdoc/>
/// <summary>
/// Creates a new instance of <see cref="HttpUserAgentParserMemoryCachedProvider"/>.
/// </summary>
/// <param name="options">The options used to set expiration and size limit</param>
public class HttpUserAgentParserMemoryCachedProvider(
HttpUserAgentParserMemoryCachedProviderOptions options) : IHttpUserAgentParserProvider
{
private readonly Microsoft.Extensions.Caching.Memory.MemoryCache _memoryCache = new(options.CacheOptions);
private readonly HttpUserAgentParserMemoryCachedProviderOptions _options = options;
/// <inheritdoc/>
public HttpUserAgentInformation Parse(string userAgent)
{
CacheKey key = GetKey(userAgent);
return _memoryCache.GetOrCreate(key, static entry =>
{
CacheKey key = (entry.Key as CacheKey)!;
entry.SlidingExpiration = key.Options.CacheEntryOptions.SlidingExpiration;
entry.SetSize(1);
return HttpUserAgentParser.Parse(key.UserAgent);
});
}
[ThreadStatic]
private static CacheKey? s_tKey;
private CacheKey GetKey(string userAgent)
{
CacheKey key = s_tKey ??= new CacheKey();
key.UserAgent = userAgent;
key.Options = _options;
return key;
}
private class CacheKey : IEquatable<CacheKey> // required for IMemoryCache
{
public string UserAgent { get; set; } = null!;
public HttpUserAgentParserMemoryCachedProviderOptions Options { get; set; } = null!;
public bool Equals(CacheKey? other) => string.Equals(UserAgent, other?.UserAgent, StringComparison.OrdinalIgnoreCase);
public override bool Equals(object? obj) => Equals(obj as CacheKey);
public override int GetHashCode() => UserAgent.GetHashCode(StringComparison.Ordinal);
}
}