using System; using System.Diagnostics.Contracts; using System.Runtime.Caching; namespace Kreta.Core { public static class Cache { private static readonly MemoryCache DefaultCache = new MemoryCache("DefaultCache"); private static readonly CacheItemPolicy DefaultPolicy = new CacheItemPolicy { SlidingExpiration = TimeSpan.FromSeconds(30) }; [Pure] public static Guid Add(object value) { var guid = Guid.NewGuid(); DefaultCache.Add(new CacheItem($"{guid}", value), DefaultPolicy); return guid; } public static bool Add(string key, object value, CacheItemPolicy cacheItemPolicy) { return DefaultCache.Add(new CacheItem(key, value), cacheItemPolicy); } public static T AddOrGetExisting(string key, T value, CacheItemPolicy cacheItemPolicy) { object existingValue = DefaultCache.AddOrGetExisting(key, value, cacheItemPolicy); return (existingValue != null) ? (T)existingValue : value; } public static void Set(string key, object value, CacheItemPolicy cacheItemPolicy) { DefaultCache.Set(new CacheItem(key, value), cacheItemPolicy); } [Pure] public static object Get(Guid guid) { return DefaultCache.Get($"{guid}"); } [Pure] public static object Get(string key) { return DefaultCache.Get(key); } [Pure] public static void Remove(string key) { try { DefaultCache.Remove(key); } catch { throw; } } } }