I am trying to implement a singleton CacheDependencyManager, by combining this CacheDependencyManager from Steve Greatrex with a singleton pattern from Jon Skeet (example 6).
I'd really appreciate any feedback on it's correctness and / or suggestions for improvement.
ExplicitCacheDependency
public class ExplicitCacheDependency : CacheDependency
{
private string _uniqueId;
public ExplicitCacheDependency(string uniqueId)
: base(new string[0]) //no file system dependencies
{
_uniqueId = uniqueId;
}
public override string GetUniqueID()
{
return _uniqueId;
}
// CacheDependency has a protected NotifyDependencyChanged method that will notify the caching framework that the cached item is no longer valid.
// In most implementations this would be invoked in some callback, but for our purposes we can just add a new Invalidate method and invoke it directly
public void Invalidate()
{
base.NotifyDependencyChanged(this, EventArgs.Empty);
}
}
CacheDependencyManager
public sealed class CacheDependencyManager
{
private static readonly Lazy<CacheDependencyManager> lazy =
new Lazy<CacheDependencyManager>(() => new CacheDependencyManager());
public static CacheDependencyManager Instance { get { return lazy.Value; } }
private CacheDependencyManager()
{
}
private Dictionary<string, ExplicitCacheDependency> _dependencies
= new Dictionary<string, ExplicitCacheDependency>();
public CacheDependency GetCacheDependency(string key)
{
if (!_dependencies.ContainsKey(key))
_dependencies.Add(key, new ExplicitCacheDependency(key));
return _dependencies[key];
}
public void InvalidateDependency(string key)
{
if (_dependencies.ContainsKey(key))
{
var dependency = _dependencies[key];
dependency.Invalidate();
dependency.Dispose();
_dependencies.Remove(key);
}
}
}