forked from gitter-badger/IdentityServer4
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDefaultCache.cs
More file actions
65 lines (57 loc) · 1.94 KB
/
DefaultCache.cs
File metadata and controls
65 lines (57 loc) · 1.94 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
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Memory;
using System;
namespace IdentityServer4.Services
{
/// <summary>
/// IMemoryCache-based implementation of the cache
/// </summary>
/// <typeparam name="T"></typeparam>
/// <seealso cref="IdentityServer4.Services.ICache{T}" />
public class DefaultCache<T> : ICache<T>
where T : class
{
const string KeySeparator = ":";
readonly IMemoryCache _cache;
/// <summary>
/// Initializes a new instance of the <see cref="DefaultCache{T}"/> class.
/// </summary>
/// <param name="cache">The cache.</param>
public DefaultCache(IMemoryCache cache)
{
_cache = cache;
}
string GetKey(string key)
{
return typeof(T).FullName + KeySeparator + key;
}
/// <summary>
/// Gets the cached data based upon a key index.
/// </summary>
/// <param name="key">The key.</param>
/// <returns>
/// The cached item, or <c>null</c> if no item matches the key.
/// </returns>
public Task<T> GetAsync(string key)
{
key = GetKey(key);
var item = _cache.Get<T>(key);
return Task.FromResult(item);
}
/// <summary>
/// Caches the data based upon a key
/// </summary>
/// <param name="key">The key.</param>
/// <param name="item">The item.</param>
/// <param name="expiration">The expiration.</param>
/// <returns></returns>
public Task SetAsync(string key, T item, TimeSpan expiration)
{
key = GetKey(key);
_cache.Set(key, item, expiration);
return Task.FromResult(0);
}
}
}