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<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
You can always reflect into the argument to get the value instead of ToString()
then declare the aspect like