Fun with cachemanager and extension methods

Topics: Caching Application Block
Apr 28, 2009 at 7:48 AM
Edited Apr 28, 2009 at 7:48 AM
I just wanted to share an extension method that adds a nice feature to ICacheManager. The method is called GetOrAddData() and takes a cache key and a function as parameters. If the key doesn't exist in the cache the function is called and the result is added to the cache.

I'm kind of a caching application block newbie so any comments are most welcome. :-)


public static class Extensions
    public static T GetOrAddData<T>(this ICacheManager cacheManager, string objectKey, Func<T> getFunction)
        if (!cacheManager.Contains(objectKey))
            var cachedItem = getFunction();
            cacheManager.Add(objectKey, cachedItem);
            return cachedItem;
            return (T)cacheManager.GetData(objectKey);

You can then retrieve items from the cache, and add if it doesn't exist in the cache, with a single line of code:
cacheManager.GetOrAddData<string>(myCacheKey, MethodThatLoadsData);

The MethodThatLoadsData, in this example, shouldn't take any parameters and return string.

 Hopefully this will be usefull to someone.


Best regards,

Apr 28, 2009 at 8:03 AM
Thanks for sharing to the community.

Sarah Urmeneta
Global Technology & Solutions
Avanade, Inc.