After much prompting from this post I wanted to build a simple, in-memory, thread-safe cache.
The only caveat (as far as I was originally concerned) was the need for two different absolute expiration times for cached objects - those being based on a property of the item being cached (IsFailureItem
). This is for a .NET Framework 4.6.1 solution.
I am primarily interested in anything which makes this either thread-unsafe, leak memory or simply bad practice. I know the class itself could be generically typed, but that is a decision for the future.
public class CacheItem
{
public IEnumerable<DataItem> Response { get; set; }
public bool IsFailureItem { get; set; }
}
public class CacheHelper
{
public static CacheHelper Cache { get; set; }
private static IMemoryCache InMemoryCache { get; set; }
static CacheHelper()
{
Cache = new CacheHelper();
InMemoryCache = new MemoryCache(new MemoryCacheOptions { });
}
private CacheHelper() { }
public CacheItem this[string key]
{
get => InMemoryCache.Get<CacheItem>(key);
set => InMemoryCache.Set<CacheItem>(key, value, value.IsFailureItem ? FailureCacheEntryOption : SuccessCacheEntryOption );
}
private static MemoryCacheEntryOptions FailureCacheEntryOption => new MemoryCacheEntryOptions()
{ AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(EnvironmentHelper.CacheFailureSecondsToLive) };
private static MemoryCacheEntryOptions SuccessCacheEntryOption => new MemoryCacheEntryOptions()
{ AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(EnvironmentHelper.CacheSuccessSecondsToLive) };
}
InMemoryCache
can be readonly field not property. Also you can remove setters from all other properties then introduce a constructor forCacheItem
. \$\endgroup\$