I've implemented a common wrapper pattern I've seen for the .NET cache class using generics as follows:
private static T CacheGet<T>(Func<T> refreashFunction, [CallerMemberName]string keyName = null)
{
if (HttpRuntime.Cache[keyName] == null)
HttpRuntime.Cache.Insert(keyName, refreashFunction(), null, DateTime.UtcNow.AddSeconds(600), System.Web.Caching.Cache.NoSlidingExpiration);
return (T)HttpRuntime.Cache[keyName];
}
It could then be called like so:
public static Dictionary<string, string> SomeCacheableProperty
{
get
{
return CacheGet(() =>
{
Dictionary<string, string> returnVal = AlotOfWork();
return returnVal;
});
}
}
However, the CacheGet
method could be implemented using dynamic:
private static dynamic CacheGet(Func<object> refreashFunction, [CallerMemberName]string keyName = null)
{
if (HttpRuntime.Cache[keyName] == null)
HttpRuntime.Cache.Insert(keyName, refreashFunction(), null, DateTime.UtcNow.AddSeconds(600), System.Web.Caching.Cache.NoSlidingExpiration);
return HttpRuntime.Cache[keyName];
}
The questions I have:
Is there a technically (or philosophically) superior preference between these two implementations?
Are these different at runtime?
If they are both left in, which one is being called in the getter method?