Cache Loading Pattern
Yesterday was my first delivery of an MSDN Webcast. My topic - Caching Strategies for ASP.NET. One of the topics I demonstrated was a Cache Loading Pattern. This blog is to provide a code-walkthrough of that discussion
First, declare a delegate to represent the cache loading method
1: public delegate object CacheLoader(string cacheItemKey);
Next, create a public static (Shared in VB.NET) method to contain the logic for determining whether an item exists in the cache or not.
1: public static object GetCacheItem(
2: string cacheItemKey,
3: CacheLoader anyCacheLoader)
4: {
5: HttpContext context = HttpContext.Current;
6: // acquire local reference of cache item
7: object cacheItem = context.Cache[cacheItemKey];
8:
9: // if local reference is null, load the cache
10: if (cacheItem==null)
11: {
12: cacheItem = anyCacheLoader(cacheItemKey);
13: // trace
14: context.Trace.Warn(cacheItemKey + " loaded from resource");
15: } else {
16: // trace
17: context.Trace.Warn(cacheItemKey + " loaded from cache");
18: }// if else
19:
20: // return
21: return cacheItem;
22:
23: }// GetCacheItem(string, CacheLoader);
As seen above, if the item does not exist, then it invokes the delegate to do the loading.
Here is an example of a method which implements the cache loading delegate signature:
1: // same signature as delegate above
2: public static object GetEmployeesXml(string cacheItemKey)
3: {
4: HttpContext context = HttpContext.Current;
5:
6: string pathToEmployeesXML =
7: context.Request.MapPath("Employees.xml");
8:
9: DataSet dataSetToReturn = new DataSet();
10: dataSetToReturn.ReadXml(pathToEmployeesXML);
11:
12: context.Cache.Insert(
13: cacheItemKey,
14: dataSetToReturn,
15: new System.Web.Caching.CacheDependency(pathToEmployeesXML));
16:
17: return dataSetToReturn;
18:
19: }// object GetEmployeesXml(string)
Finally, here is an example of how to use the cache loading method:
1: anyDataGrid.DataSource =
2: CacheLoaders.GetCacheItem("Employees.Xml",
3: new CacheLoader(CacheLoaders.GetEmployeesXml));
The benefit to all of this is the caching behaviour is contained in the various methods which match the delegate signature.
Thus, one method may load from an underlying resource and place the content in the cache based on a dependency,
whereas another method may load from the resource and put in an absolute expiration.
But the logic to determine if the cache exists or not is in only one location!
I would really like some feedback on this...