Files
SkydiveLogs/Back/skydiveLogs-api.DomainBusiness/CacheService.cs
2021-08-11 22:37:14 +02:00

51 lines
1.4 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 Methods
public bool Contains(CacheType type, int userId = 0)
{
var key = GetKey(userId, type);
return MemoryCache.Default[key.ToString()] != null;
}
public void Delete(CacheType type, int userId = 0)
{
var key = GetKey(userId, type);
MemoryCache.Default.Remove(key.ToString());
}
public T Get<T>(CacheType type, int userId = 0)
{
var key = GetKey(userId, type);
return (T)MemoryCache.Default[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.Default.Set(key.ToString(), value, policy);
}
private string GetKey(int userId, CacheType type)
{
return $"{userId}-{type}";
}
#endregion Public Methods
}
}