Search code examples
cachingcastle-dynamicproxyinvocation

Castle Core Invocation create a cache key from intercepted method


I'm using a interface interceptor to cache all methods that starts with "Get" but i can't figure out how to generate a unique cache key for every unknown parameter it can be anything and using GetHashCode is not an option as i can't be 100% sure that they have overridden the GetHashCode.

some thoughts was someting in the line of How can I create a unique hashcode for a JObject?

where JSON is used for a JObject i was thinking on JSON serialize every parameter then get the hash code like explained in the link above:

var obj = JToken.Parse(jsonString);
var comparer = new JTokenEqualityComparer();
var hashCode = comparer.GetHashCode(obj);

However i think this will be a performence hit so how can this be solved ?

The code i have so far is this but it wont handle the complex type situation where .ToString won't generate the raw value type like int, string etc.

private string CreateCacheKey(IInvocation invocation)
{
    string className = invocation.TargetType.FullName;
    string methodName = invocation.Method.Name;

    var builder = new StringBuilder(100);
    builder.Append(className);
    builder.Append(".");
    builder.Append(methodName);

    for (int i = 0; i < invocation.Arguments.Length; i++)
    {
        var argument = invocation.Arguments[i];
        var argumentValue = invocation.GetArgumentValue(i);
        builder.Append("_");
        builder.Append(argument);

        if (argument != argumentValue)
        {
            builder.Append(argumentValue);
        }
    }

    return string.Format("{0}-{1}", this.provider.CacheKey, builder);
}

Solution

  • I ended up using GetHashCode as it is the only viable solution if thay dont override the method it will not cache.