Skip to content

Commit 731bb39

Browse files
calin-lupas_dsamcapscalin-lupas_dsamcaps
authored andcommitted
Add caching mechanism with CacheService implementation
Introduce a caching mechanism by adding a `CacheService` that implements the `ICacheService` interface. Register the memory cache in `ServiceExtensions.cs` and provide methods for getting, setting, and removing cached items in `CacheService.cs`. Define the caching contract in `ICacheService.cs`.
1 parent cbb919b commit 731bb39

3 files changed

Lines changed: 55 additions & 0 deletions

File tree

src/DevExcelerateApi/Core/Extensions/ServiceExtensions.cs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,9 @@ internal static IServiceCollection AddAppServices(this IServiceCollection servic
9898
services.AddSingleton<ITeamService, TeamService>();
9999
services.AddSingleton<IIssueService, IssueService>();
100100

101+
builder.Services.AddMemoryCache();
102+
builder.Services.AddSingleton<ICacheService, CacheService>();
103+
101104
return services;
102105
}
103106

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
using Microsoft.Extensions.Caching.Memory;
2+
3+
namespace DevExcelerateApi.Services
4+
{
5+
public class CacheService(IMemoryCache memoryCache) : ICacheService
6+
{
7+
private readonly IMemoryCache _memoryCache = memoryCache;
8+
9+
public Task<T?> GetAsync<T>(string key)
10+
{
11+
_memoryCache.TryGetValue(key, out T? value);
12+
return Task.FromResult(value);
13+
}
14+
15+
public Task SetAsync<T>(string key, T value, TimeSpan? absoluteExpireTime = null, TimeSpan? slidingExpireTime = null)
16+
{
17+
var options = new MemoryCacheEntryOptions();
18+
19+
if (absoluteExpireTime.HasValue)
20+
{
21+
options.AbsoluteExpirationRelativeToNow = absoluteExpireTime;
22+
}
23+
else if (slidingExpireTime.HasValue)
24+
{
25+
options.SlidingExpiration = slidingExpireTime;
26+
}
27+
else
28+
{
29+
// Default expiration if none provided
30+
options.SlidingExpiration = TimeSpan.FromMinutes(5);
31+
}
32+
33+
_memoryCache.Set(key, value, options);
34+
return Task.CompletedTask;
35+
}
36+
37+
public Task RemoveAsync(string key)
38+
{
39+
_memoryCache.Remove(key);
40+
return Task.CompletedTask;
41+
}
42+
}
43+
}
Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
namespace DevExcelerateApi.Services
2+
{
3+
public interface ICacheService
4+
{
5+
Task<T?> GetAsync<T>(string key);
6+
Task SetAsync<T>(string key, T value, TimeSpan? absoluteExpireTime = null, TimeSpan? slidingExpireTime = null);
7+
Task RemoveAsync(string key);
8+
}
9+
}

0 commit comments

Comments
 (0)