using System; using Microsoft.Practices.EnterpriseLibrary.Caching; namespace Website.Caching { public abstract class CacheBase { private const string KEY_FORMAT = "{0}_{1}"; protected internal readonly ICacheManager cache; private readonly string prefix; protected CacheBase(string prefix) : this(null, prefix) { } protected CacheBase(ICacheManager cache, string prefix) { if (cache == null) { // Try to get the default cache manager cache = CacheFactory.GetCacheManager(); // If it's still null, bail out now if (cache == null) throw new ArgumentNullException("cache", "No cache manager was provided! Try configuring a Default Cache manager"); } this.cache = cache; this.prefix = prefix; } protected object this[string key] { get { var customKey = GetCustomKey(key); return cache.Contains(customKey) ? cache[customKey] : null; } set { // You can't set an empty key! if (string.IsNullOrEmpty(key)) return; var customKey = GetCustomKey(key); // See if we've got anything in there now if (cache.Contains(customKey)) cache.Remove(customKey); // Can only cache non-null values if (value != null) cache.Add(customKey, value); } } public void ClearCachedItems() { cache.Flush(); } protected internal string GetCustomKey(string key) { if (string.IsNullOrEmpty(key)) throw new ArgumentNullException("key", "Cache keys can not be null or empty!"); return string.Format(KEY_FORMAT, prefix, key); } } public abstract class CacheBase : CacheBase { protected CacheBase(ICacheManager cache, string prefix) : base(cache, prefix) { } protected new T this[string key] { get { return (T)base[key]; } set { base[key] = value; } } } }