Just wanted to share something I’m using for creating cache key’s.
so typically I use this kind of thing:
var cacheKey = UrnId.Create<MyDTO>(req.PropA);
trouble is, if the name has FieldSeperator char in it, it will throw an exception so you end up calling .Replace() to clean them up.
…then there are times when I have a more complex cache key that is basically every public property like
var cacheKey = UrnId.Create<MyDTO>($$"{req.PropA}_{req.PropB}_{req.PropC}");
the code begins to not be so nice so I’ve been using this library to help me generate value based hashcodes for the cache keys with the following extension methods
public static string GetValueHashCode<T>(this T instance)
{
return UrnId.Create<T>(FieldwiseHasher.Hash(instance));
}
public static string GetValueHashCode<T, TValue>(this T instance, Expression<Func<T, TValue>> selector)
{
var invoke = selector.Compile().Invoke(instance);
return UrnId.Create<T>(FieldwiseHasher.Hash(invoke));
}
and used like
public object Any(MyDTO req)
{
// hashes all public props of type (include base type)
var cacheKey = req.GetValueHashCode();
// hashes single prop value
var cacheKey = req.GetValueHashCode(x => x.PropA);
// hashes anon prop values
var cacheKey = req.GetValueHashCode(x => new { x.PropA, x.PropB });
return RequestContext.ToOptimizedResultUsingCache(
Cache,
cacheKey,
...
}
There are some caveats for the hashcode generation but for my needs, it seems to work fine.