using System;
using System.Collections.Concurrent;
namespace Umbraco.Core.Cache
{
///
/// Used to get/create/manipulate isolated runtime cache
///
///
/// This is useful for repository level caches to ensure that cache lookups by key are fast so
/// that the repository doesn't need to search through all keys on a global scale.
///
public class IsolatedRuntimeCache
{
internal Func CacheFactory { get; set; }
///
/// Constructor that allows specifying a factory for the type of runtime isolated cache to create
///
///
public IsolatedRuntimeCache(Func cacheFactory)
{
CacheFactory = cacheFactory;
}
private readonly ConcurrentDictionary _isolatedCache = new ConcurrentDictionary();
///
/// Returns an isolated runtime cache for a given type
///
///
///
public IRuntimeCacheProvider GetOrCreateCache()
{
return _isolatedCache.GetOrAdd(typeof(T), type => CacheFactory(type));
}
///
/// Returns an isolated runtime cache for a given type
///
///
public IRuntimeCacheProvider GetOrCreateCache(Type type)
{
return _isolatedCache.GetOrAdd(type, t => CacheFactory(t));
}
///
/// Tries to get a cache by the type specified
///
///
///
public Attempt GetCache()
{
IRuntimeCacheProvider cache;
if (_isolatedCache.TryGetValue(typeof(T), out cache))
{
return Attempt.Succeed(cache);
}
return Attempt.Fail();
}
///
/// Clears all values inside this isolated runtime cache
///
///
///
public void ClearCache()
{
IRuntimeCacheProvider cache;
if (_isolatedCache.TryGetValue(typeof(T), out cache))
{
cache.ClearAllCache();
}
}
///
/// Clears all of the isolated caches
///
public void ClearAllCaches()
{
foreach (var key in _isolatedCache.Keys)
{
IRuntimeCacheProvider cache;
if (_isolatedCache.TryRemove(key, out cache))
{
cache.ClearAllCache();
}
}
}
}
}