Attribute Based Caching for .NET
Attribute Based Caching is a new caching library that Adam Bell released recently on codeplex; it provides automatic method caching for .NET through the use of attributes. Caching in applications is frequently done imperatively. That is, by writing code in many places that checks a cache prior to making an expensive call and fills the cache afterwards. Attribute Based Caching gives you this functionality just by placing a [Cache.Cacheable] attribute on the method.
Cache invalidation is also handled declaratively. When marking a method as cached, a unique key can be chosen. Another method can be marked as invalidating that same cache key, as shown below.
public DataTable GetAllTransactionsForUser(int userId)
return new DataProvider().GetAllTransactionsForUser(userId);
public void ClearTransactionCache(int userId)
A number of settings can be applied to the attributes in order to control cache functionality. CacheSettings.IgnoreParameters ties all calls to a method to the same cache key for methods where the result should not be cached by the method’s parameter values. CacheSettings.UseId forms the cache key using the Id property of the method parameter. CacheSettings.UseProperty lets the developer specify a method parameter to be used to form the cache key. New in release 1.2.1 is IgnoreTTL, which sets the marked method’s cache to never expire. This release also adds the ability to cache method calls with ICollection parameters.
Three main cache implementations are provided. InProcessMemoryCache is implemented as a dictionary, BTreeCache is a binary tree that saves itself to disk, and OutOfProcessMemoryCache uses Microsoft ApplicationServer.Caching. Which cache to use can be set via configuration file or directly from code. The ICache interface is available to make your own cache type if the provided caches are not sufficient.
Internally, Attribute Based Caching uses postsharp to intercept method calls. Postsharp is a library that allows creation of attributes which run code at specific points during execution. An attribute can be set to run before the method its assigned to executes any code, after execution, when an exception is thrown, etc. The end result for Attribute Based Caching is that when a cached version (by method and its relevant parameters) exists, the cached value is returned instead of calling the method.
Attribute Based Caching is offered under the New BSD License, which allows unlimited redistribution for any purpose as long as its copyright notices and the license's disclaimers of warranty are maintained.
Yoni Goldberg Oct 30, 2014
Dmytro Svarytsevych Oct 30, 2014