CacheHelper for interdependant Cache entries in ASP.Net
This class will let you manage a group of cache entries, creating an additionl dependency for each item added.
All of the items from a group of caches can be cleared together. It doesn't replaces the cache, it only affects how items get added.
Using it in an ASP.Net page:
protected void Page_Load(object sender, EventArgs e)
{
ShowCacheStuff();
}
private void ShowCacheStuff()
{
if
(Cache["test"] == null)
{
CacheHelper.Group("TestGroup").Insert("test",
DateTime.Now.ToString());
}
Response.Write(Cache["test"]);
Response.Write("<hr>");
}
protected void Button1_Click(object sender, EventArgs
e)
{
CacheHelper.Group("TestGroup").Clear();
ShowCacheStuff();
}
using System;
using System.Web;
using
System.Web.Caching;
namespace AndrewSeven.Examples
{
///
<summary>
/// Provides a simple way to add
interdependant items to the Cache
///
</summary>
public class CacheHelper
{
private
string groupDependencyCacheKey;
static
readonly string fullName =
typeof(CacheHelper).FullName;
static public
CacheHelper Group(string name)
{
return new
CacheHelper(name);
}
private
CacheHelper(string name)
{
groupDependencyCacheKey = fullName + "::" + name;
}
public
Cache Cache
{
get
{
return
HttpContext.Current.Cache;
}
}
private
void EnsureDependencyItem()
{
if
(Cache[groupDependencyCacheKey] == null)
{
Cache[groupDependencyCacheKey] = DateTime.Now;
}
}
public
void Clear()
{
Cache[groupDependencyCacheKey]
= DateTime.Now;
}
static public void
Clear(string groupName)
{
Group(groupName).Clear();
}
public
CacheDependency GetDependency(CacheDependency
dependency)
{
EnsureDependencyItem();
return
new CacheDependency(null,(new string[]
{groupDependencyCacheKey}),dependency);
}
public
CacheDependency GetDependency()
{
return
GetDependency(null);
}
public void
Insert(string key,object value)
{
Cache.Insert(key,value,GetDependency());
}
public
void Insert(string key,object value,CacheDependency
dependency)
{
Cache.Insert(key,value,GetDependency(dependency));
}
public
void Insert(string key,object value,int
durationSeconds)
{
Cache.Insert(key,value,GetDependency(),System.DateTime.MaxValue,TimeSpan.FromSeconds(durationSeconds));
}
}
}