Skip to main content

Caching as Cross-Cutting Concern Part 2 – Invalidating the Cache

 

In my previous post I showed how you can very easily add Caching to your application by using Castle Windsor.

The example used was a very basic implementation and whilst it can be useful for a large number of cases it didn’t cover the all important cache invalidation.

In this post I hope to explain how with a bit of convention over configuration how you can invalidate your cache when an object changes.

In the last post I was using the Method name combined with the arguments to build the cache key. Now to allow us to build a cache key that can be used when invalidating the cache the key needs to be related to the Result type.

For this I’m going to create a simple interface called IAmCacheable to identify the object we want to cache.

    public interface IAmCacheable
    {
        object Key { get; }
    }

And make sure the object we want to cache implements this interface.

    public class Product : IAmCacheable 
    {
        public object Key { get; }

        public string Name { get; set; }
    }

Now we have to change the CacheInterceptor  to build the Cache Key based on the combination of the Type and the Id.

   public class CacheInterceptor : IInterceptor
   {
       private readonly ICacheProvider cacheProvider;

       private const int CacheExpiryMinutes = 1; 

       public CacheInterceptor(ICacheProvider cacheProvider)
       {
           this.cacheProvider = cacheProvider; 
       }

       #region IInterceptor Members

       public void Intercept(IInvocation invocation)
       {
           //check if the method has a return value
           if (invocation.Method.ReturnType == typeof(void))
           {
               invocation.Proceed();
               return; 
           }

           //check to see if the return type implements IAmCacheable
           var returnTypeIsCacheable = typeof (IAmCacheable)
               .IsAssignableFrom(invocation.Method.ReturnType); 

           if (!returnTypeIsCacheable)
           {
               invocation.Proceed();
               return;
           }

           var cacheKey = BuildCacheKeyFrom(invocation); 
          
           //try get the return value from the cache provider
           var item = cacheProvider.Get(cacheKey); 

           if (item != null)
           {
               invocation.ReturnValue = item;
               return;
           }

           //call the interecepted method
           invocation.Proceed();

           if (invocation.ReturnValue != null)
           {
               cacheProvider.Put(cacheKey, CacheExpiryMinutes, invocation.ReturnValue); 
           }

           return;
       }

       #endregion

       private static string BuildCacheKeyFrom(IInvocation invocation)
       {
           var cacheableTypeName = invocation.Method.ReturnType.Name;
           var cacheKey = "{0}-{1}";

           var keyArgName = "id";

           var prms = invocation.Method.GetParameters();

           var keyIndex = prms.TakeWhile(prm => prm.Name != keyArgName).Count();

           var keyValue = invocation.Arguments[keyIndex]; 

           return string.Format(cacheKey, cacheableTypeName, keyValue); 

       }

   }

The main change here is in the BuildCacheKeyFrom method. What I’m doing here is looking for the value of the Argument named “id” and using this combined with the Type name to build the key which would end up like “Product-1”.

Now that we’ve changed the logic to build the Cache Key we need to be remove the object from the Cache when it changes.

Similar to the IMustBeCached interface in the first article we create an interface called IInvalidateCache to identity which call to apply the invalidation interceptor on.

   public interface IInvalidateCache
   {
   }

 

And we’ll make the IProductRepository implement this like so.

    public interface IProductRepository : IInvalidateCache
    {
        Product Get(int id);

        void Update(Product product);
    }

 

Now we need a new type of Interceptor called CacheInvalidationInterceptor which removes any IAmCacheable objects from the cache when they are passed as arguments to any method.

    public class CacheInvalidationInterceptor : IInterceptor
    {
        private readonly ICacheProvider cacheProvider;

        public CacheInvalidationInterceptor(ICacheProvider cacheProvider)
        {
            this.cacheProvider = cacheProvider;
        }

        #region IInterceptor Members

        public void Intercept(IInvocation invocation)
        {
            //check to see if any argument implements IAmCacheable
            var hasCacheableArgument = invocation.Arguments.Any(a => a is IAmCacheable);

            if (!hasCacheableArgument)
            {
                invocation.Proceed();
                return;
            }

            //call the intercepted method
            invocation.Proceed();

            var cacheKey = BuildCacheKeyFrom(invocation);

            //remove the item from the cache
            cacheProvider.Remove(cacheKey); 

            return;
        }

        #endregion

        private static string BuildCacheKeyFrom(IInvocation invocation)
        {
            var cacheable = invocation.Arguments.First(a => a is IAmCacheable) as IAmCacheable; 

            var cacheableTypeName = cacheable.GetType().Name;

            var cacheKey = "{0}-{1}";

            return string.Format(cacheKey, cacheableTypeName, cacheable.Key);

        }

    }

All we do here is look for any Arguments which implement IAmCacheable and then use a combination of the Type name and the IAmCacheable.Key to build the cache key.

We also make sure the method is called first by calling Invocation.Proceed before removing the item from the Cache.

Finally we need to wire up this new Interceptor in the Bootstrapper.

        public void Configure()
        {
            container = new WindsorContainer();

            container.Register(
                Component.For<CacheInterceptor>(),
                Component.For<ICacheProvider>()
                    .ImplementedBy<WebCacheProvider>().LifeStyle.Singleton,
                Component.For<ICatalogQueryService>()
                    .ImplementedBy<CatalogQueryService>()
                    .LifeStyle.Transient
                    .Interceptors(new InterceptorReference(typeof(CacheInterceptor))).Anywhere);


            container.Register(
                Component.For<CacheInvalidationInterceptor>(),
                Component.For<IProductRepository>()
                    .ImplementedBy<ProductRepository>()
                    .LifeStyle.Transient
                    .Interceptors(new InterceptorReference(
                        typeof(CacheInvalidationInterceptor)))
                        .Anywhere);


        }

 

This is my final post on the subject. Hope this gives you some ideas on how to implement Caching or other Cross-Cutting concerns using AOP.

Till next time.

Comments

Popular posts from this blog

Freeing Disk Space on C:\ Windows Server 2008

I just spent the last little while trying to clear space on our servers in order to install .NET 4.5. Decided to post so my future self can find the information when I next have to do this. I performed all the usual tasks: Deleting any files/folders from C:\windows\temp and C:\Users\%UserName%\AppData\Local\TempDelete all EventViewer logs Save to another Disk if you want to keep themRemove any unused programs, e.g. FirefoxRemove anything in C:\inetpub\logsRemove any file/folders C:\Windows\System32\LogFilesRemove any file/folders from C:\Users\%UserName%\DownloadsRemove any file/folders able to be removed from C:\Users\%UserName%\DesktopRemove any file/folders able to be removed from C:\Users\%UserName%\My DocumentsStop Windows Update service and remove all files/folders from C:\Windows\SoftwareDistributionDeleting an Event Logs Run COMPCLN.exe Move the Virtual Memory file to another disk However this wasn’t enough & I found the most space was cleared by using the Disk Cleanup to…

CPF Contribution Rates for new Singapore Permanent Residents (SPR’s)

Recently my wife and I applied and got approved for Singapore Permanent Residency. After completing the formalities the most significant immediate change is the contribution to CPF which is Singapore’s mandatory social security savings scheme requiring contributions from employers and employees. CPF contributions start from the date you obtain SPR status, which is the date of the entry permit.   Being a relentless budgeter I needed to know exactly how much I and my employer would have to contribute so that I could adjust my budget accordingly as the employee contributions get deducted from the monthly salary. After doing some research I discovered that there is a “graduated” approach to CPF contributions for new SPR’s where the contributions gradually increase in the first and second year and then upon reaching the third year are at the full amount. Note: There is an option for employers to contribute the full amount for year 1 and year 2 and the employee can use the graduated rate, b…

Consuming the SSRS ReportExecutionService from a .NET Client

I’ve just finished writing a nice wrapper which internally calls the SSRS ReportExecutionService to generate reports.
Whilst it was fairly simple to implement there has been some major changes between 2005 and 2008 and the majority of online and documentation is based on the 2005 implementation. The most important change is that the Report Server and Report Manager are no longer hosted in IIS which will be a welcomed change to Sys Admins but makes the security model and hosting model vastly different. So far I’ve yet to figure out how to allow Anonymous Access, if anyone knows how to do this leave a comment and it will be most appreciated. Getting StartedTo get started you’ll want to add a service reference to http://localhost/ReportServer_SQL2008/ReportExecution2005.asmx where ReportServer_SQL2008 is the name you configure in the Reporting Services Configuration Manager. The Web Application files are located in C:\Program Files\Microsoft SQL Server\MSRS10.SQL2008\Reporting Servic…