Created
April 11, 2013 16:19
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!