using Microsoft.Practices.EnterpriseLibrary.Caching;
namespace Website.Caching
{
///
/// A simple wrapper around any IContentProvider that provides caching of the information
/// provided by that provider.
///
public class CachingContentProvider : CacheBase, IContentProvider
{
private const string CACHE_MANAGER_PREFIX = "ContentProvider";
private const string ID_KEY_FORMAT = "ContentID_{0}";
private static readonly object __CACHE_LOCK = new object();
private readonly IContentProvider _provider;
protected IContent this[int contentId]
{
get { return this[string.Format(ID_KEY_FORMAT, contentId)]; }
set { this[string.Format(ID_KEY_FORMAT, contentId)] = value; }
}
public CachingContentProvider(IContentProvider provider) : this(provider, null)
{
}
public CachingContentProvider(IContentProvider provider, ICacheManager cache)
: base(cache, CACHE_MANAGER_PREFIX)
{
_provider = provider;
}
public IContent GetById(int id)
{
var content = this[id];
if (content == null)
{
lock (__CACHE_LOCK)
{
if (this[id] == null)
this[id] = _provider.GetById(id);
}
content = this[id];
}
return content;
}
public IContent GetByAlias(string alias)
{
var content = this[alias];
if (content == null)
{
lock (__CACHE_LOCK)
{
if (this[alias] == null)
this[alias] = _provider.GetByAlias(alias);
}
content = this[alias];
}
return content;
}
public void Save(IContent content)
{
_provider.Save(content);
lock (__CACHE_LOCK)
{
// Clear the cached version (if any) so that
// it is reloaded from the source on the next request
this[content.ID] = null;
if(!string.IsNullOrEmpty(content.Alias))
this[content.Alias] = null;
}
}
}
}