Spring.Net Cache & Complex Keys

So you want to cache the results of a service dll using the Spring.NET CacheResult attribute… But your class takes a List or complex object as part of the method call. No worries, you can use a helper class to generate your cache keys for you!

So my problem, I wanted to cache the result of this method call:

No problem, I’ll just slap a CacheResult attribute on the method and have Spring do the work for me!

All looks good! AspNetCache is defined in my Spring.Config to use the built in ASPNetCache and the CacheKey is generated using SpEL (Spring Expression Language). It can do nice things like get property values on your object if you pass in a complex type, or test conditions. Read up if you are not familiar with the syntax.

Well after some testing all is not well. All calls to the method are resulting in the same data being returned. So i do a little bit of debugging and find this!

Well I guess SpEL doesnt magicly handle collections when creating a cache key. After some digging I discover that SpEL can invoke CLR objects! This means we can use a helper class to generate the cache key. This has the added bonus of letting us toss some tests around the key generation since this could have quite easilly slipped out into production if we were not careful.

CacheKeyHelper to the rescue.

So lets change tha Key string so it uses this new calss.

Well that doesnt work. SpEL doesnt cleanly handle generics yet. Then I remember that SpEL can invoke objects that are registered in the spring config using @(ID_NAME).Method syntax.

XML to the rescue!

So I declare an instance of the CacheKeyHelper class for string types, and I modify my CacheResult attribute to use this new instance.