Files
SkydiveLogs/Back/skydiveLogs-api.DomainBusiness/CacheService.cs
Sébastien André 143127cd01 Add a cache system on the referential info
+ Add an identity service
2021-04-17 22:17:45 +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 id = 0)
{
var key = GetKey(id, type);
return MemoryCache.Default[key.ToString()] != null;
}
public void Delete(CacheType type, int id = 0)
{
var key = GetKey(id, type);
MemoryCache.Default.Remove(key.ToString());
}
public T Get<T>(CacheType type, int id = 0)
{
var key = GetKey(id, type);
return (T)MemoryCache.Default[key.ToString()];
}
public void Put(CacheType type, object value, int duration, int id = 0)
{
var key = GetKey(id, 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 id, CacheType type)
{
return $"{id}-{type}";
}
#endregion Public Methods
}
}