CachedAttribute Behaviour

Jan 4, 2010 at 9:23 PM

The CachedAttribute is documented as:


    /// <summary>
    /// A PostSharp aspect that will cache the return value of a method or property. The aspect can 
    /// be applied with no paraemters, in which case a single return value is cached for the method, or
    /// with a varyByParameter method, which will result in a separate cached value for each input value of
    /// the named parameter.
    /// </summary>


My question is, what's the deal with this "varyByParameter"?

As far as I can tell, there is only one constructor method on this attribute:


        /// <summary>
        /// Initializes a new instance of the CachedAttribute class.
        /// </summary>
        /// <param name="cache">
        /// The name of the cache to store the data
        /// </param>
        public CachedAttribute(CacheName cache)
            this.cache = cache;


and the OnInvocation method always calls the GetCacheKey method with the MethodInvocationEventArgs:

        public override void OnInvocation(MethodInvocationEventArgs eventArgs)
// Get the full cache key
CacheKey fullCacheKey = this.GetCacheKey(eventArgs);

// ...


and the GetCacheKey method itself seems to always construct the fullCacheKey using the eventArgs params:

        private CacheKey GetCacheKey(MethodInvocationEventArgs eventArgs)
            var fullCacheKey = new StringBuilder(this.cacheKey);

            object[] arguments = eventArgs.GetArgumentArray();

            // ...

Am I missing something?

How can we config the attribute insAtance to specify which parameters should be used to determine whether a method invocation needs caching?

I'm not very familiar with PostSharp, so I apologize if I've pulled a n00b.

Thank you in advance for your help, and the great community contribution!

Best regards,


Jan 4, 2010 at 11:06 PM

Nope, you haven't pulled a n00b, and your interpretation of the code is spot on - the comment is out of date. The very first cut of the aspect allowed you to specify which parameters should be used as part of the cache key, but it didn't take long to realise that this was pretty stupid and you had to use all of the parameters to make the aspect worth having. 

So sorry about the confusion - I'll clean up the comment.



Jan 5, 2010 at 11:28 PM

Great, thank you Jon!