开发者

PostSharp - Dynamic Cache Keys

I am trying the CacheAttribute feature of PostSharp.

Following is the method I am using to build cache keys for each cache entry.

    private string BuildCacheKey(Arguments arguments)
    {
        var sb = new StringBuilder();
        sb.Append(_methodName);
        foreach (var argument in arguments.ToArray())
        {
            sb.Append(argument == null ? "_" : argument.ToString());
        }
        return sb.ToString();
    }

Below is a sample class that I use.

class State
{
    public string Code { get; set; }
    public string Name { get; set; }
}

And the method that needs to be cached is:

    [Cache]
    private static IDictionary<string, string> GetStateRegions(IEnumerable&开发者_如何学编程lt;State> states)
    {
        //some db call here to retrieve values;
    }

And this is how I call the method:

        IList<State> states = new List<State>();

        states.Add( new State {Code = "NM", Name = "New Mexico"});
        states.Add(new State {Code = "CA", Name = "California"});  

        GetStateRegions(states);

The BuildCacheKey method builds the following cache key - "GetStateRegionsSystem.Collections.Generic.List`1[ConsoleApplication1.State]"

I would like to have the cache key built something like "GetStateRegions[ConsoleApplication1.State]" - for example for the above call- "GetStateRegionsNMCA[ConsoleApplication1.State]" for state codes NM and CA.

What would be a good approach to achieve this? Also is it possible to use different logic to build keys for different methods (based on method arguments type)? Would greatly appreciate any pointers/suggestions.


The issue you'll have is that you wont know what the arguments are unless of course you're only using this on a single method. You can use MethodInfo.Name in a switch statement if you want to change your key stratgey. You might want to use a delegate and specify the key building method when you declare the aspect.

You can try using

if(Argument is List<State>) 
{
 //gen key based ons tates
} else
{
//gen key based on ToString()
}

You can always reflect into the argument to get the value instead of ToString()

[serializable]
public class MyAspect : OnMethodBoundaryAspect
{
   public MyKeyBuilderDelegate KeyBuildMethod;

  ...
}

then declare the aspect like

[MyAspect(KeyBuilderMethod = BuildByState)]
public void MyMethod() { ... }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜