MemoryCacheRepository
Represents a class object used to provide memory-based cache.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
namespace Relativity.DataExchange
{
[DebuggerStepThrough]
internal class MemoryCacheRepository : IObjectCacheRepository, IDisposable
{
private static readonly TimeSpan DefaultExpirationTimeSpan = TimeSpan.FromHours(1);
private readonly MemoryCache cache;
private bool disposed;
public long Count => cache.GetCount((string)null);
public TimeSpan Expiration { get; set; }
public MemoryCacheRepository()
: this(DefaultExpirationTimeSpan)
{
}
public MemoryCacheRepository(TimeSpan expiration)
: this(MemoryCache.get_Default(), expiration)
{
}
public MemoryCacheRepository(MemoryCache cache, TimeSpan expiration)
{
if (cache == null)
throw new ArgumentNullException("cache");
this.cache = cache;
Expiration = expiration;
}
public void Clear()
{
((IEnumerable<KeyValuePair<string, object>>)cache).ToList().ForEach(delegate(KeyValuePair<string, object> a) {
cache.Remove(a.Key, (string)null);
});
}
public bool Contains(string key)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException("key");
return cache.Contains(key, (string)null);
}
public void Delete(string key)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException("key");
if (cache.Contains(key, (string)null))
cache.Remove(key, (string)null);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
public TEntity SelectByKey<TEntity>(string key)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException("key");
return (TEntity)cache.Get(key, (string)null);
}
public void Upsert(string key, object value)
{
Upsert(key, value, Expiration);
}
public void Upsert(string key, object value, TimeSpan expiration)
{
if (string.IsNullOrEmpty(key))
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
CacheItemPolicy val = new CacheItemPolicy();
val.set_AbsoluteExpiration(DateTimeOffset.Now.Add(expiration));
CacheItemPolicy val2 = val;
cache.Set(key, value, val2, (string)null);
}
public override string ToString()
{
StringBuilder stringBuilder = new StringBuilder();
foreach (KeyValuePair<string, object> item in (IEnumerable<KeyValuePair<string, object>>)cache) {
if (stringBuilder.Length > 0)
stringBuilder.Append(";");
stringBuilder.AppendFormat("{0}={1}", item.Key, item.Value);
}
return stringBuilder.ToString();
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
disposed = true;
}
}
}