Skip to content

Instantly share code, notes, and snippets.

@jeff-french
Created April 11, 2013 16:19
Show Gist options
  • Save jeff-french/5364818 to your computer and use it in GitHub Desktop.
Save jeff-french/5364818 to your computer and use it in GitHub Desktop.
Extension method for ServiceStack ICacheClient that fetches an item from the cache or adds it if it is not there.
public static T GetOrAdd<T>(this ICacheClient cache, string key, DateTime expiresAt, Func<T> getItemToCacheDelegate)
{
T item;
var itemIsInCache = !cache.Add(key, "", expiresAt);
if (itemIsInCache)
{
item = cache.Get<T>(key);
}
else
{
item = getItemToCacheDelegate();
cache.Set(key, item, expiresAt);
}
return item;
}
@jeff-french
Copy link
Author

I'm using the success or failure of the Add call to determine if the item is already in the cache. This is to account for value types. If I simply do a Get on the item and check for null I will get the wrong result for a value type that is not actually in the cache yet (default value). The downside of this implementation is the extra trip to the cache. Any ideas for improvement are welcome!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment