Tuesday 14 October 2008

Microsoft Enterprise Library #5 – Cache Management

So I had a look into the caching applicaiton block and was impressed with some of the things that it could do. After this I went on a practical use adventure in which I hit a couple of road blocks, so I thought I'd blog about them. In this case I came across a problem where for each object I'm referencing by key I need to setup a new Cache Manager in the application block. If I have to do this for each object I wish to cache I'm going to have a very large cache config file that I don't really want to have to manage. So here is how I got around it. I created a Key class that held the unique information about my object.

class CacheKey
{
 public object Id {get;set;}
 public Type {get;set;}

 public override string ToString()
 {
  return type.ToString() + "." + id.ToString();
 }
}
In my cache interface I have methods to create a generic cached object like so.

interface ICache
{
 void UpdateCache(object key, object objectToCache);

 void UpdateCache(object key, object objectToCache, CacheManager manager);

 object GetObjectFromCache(object key, Type objectType);

 object GetObjectFromCache(object key, Type objectType, CacheManager manager);
}
So in my implementation I would do the following.

public void UpdateCache(object key, object objectToCache)
{
 CacheKey keyObj = new CacheKey();
 keyObj.Id = key.ToString();
 keyObj.Type = objectToCache.GetType();
 
 ICacheManager defaultCache = CacheFactory.GetCacheManager("DefaultManager");
 defaultCache.Add(keyObj.ToString(), objectToCache);
}

object GetObjectFromCache(object key, Type objectType)
{
 CacheKey keyObj = new CacheKey();
 keyObj.Id = key;
 keyObj.Type = objectType;

 object returnObject = userCache.GetData(keyObj.ToString());
}
If I want to handle multiple managers then I just pass through the manager to the methods from the interface when I implement them. This allows me to use the same rule for every object in the default cache without setting up a specific rule for each object I want to cache. There are some disadvantages to this method. I wouldn't recommend that you use this for large volumes of data as it could slow down your cache. Keep large volumes in their own rules, I.E. for postal codes (or zip codes for americans), you don't want searching throuh the possible zip codes to find your logged in user details to slow you down.

No comments: