Files
SkydiveLogs/Back/skydiveLogs-api.DomainBusiness/CacheService.cs
2022-05-08 16:42:04 +02:00

66 lines
1.7 KiB
C#

using skydiveLogs_api.Domain;
using skydiveLogs_api.DomainBusiness.Interfaces;
using System;
using System.Runtime.Caching;
namespace skydiveLogs_api.DomainBusiness
{
public class CacheService : ICacheService
{
#region Public Constructors
public CacheService()
{
_memoryCache = MemoryCache.Default;
}
#endregion Public Constructors
#region Private Fields
private readonly MemoryCache _memoryCache;
#endregion Private Fields
#region Public Methods
public bool Contains(CacheType type, int userId = 0)
{
var key = GetKey(userId, type);
return _memoryCache.Contains(key.ToString());
}
public void Delete(CacheType type, int userId = 0)
{
var key = GetKey(userId, type);
_memoryCache.Remove(key.ToString());
}
public T Get<T>(CacheType type, int userId = 0)
{
var key = GetKey(userId, type);
return (T)_memoryCache.Get(key.ToString());
}
public void Put(CacheType type, object value, int duration, int userId = 0)
{
var key = GetKey(userId, type);
if (duration <= 0)
throw new ArgumentException("Duration cannot be less or equal to zero", "duration");
var policy = new CacheItemPolicy
{
AbsoluteExpiration = DateTime.Now.AddMilliseconds(duration)
};
_memoryCache.Set(key.ToString(), value, policy);
}
private string GetKey(int userId, CacheType type)
{
return $"{userId}-{type}";
}
#endregion Public Methods
}
}