Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CacheDependency from 2 or more other cache items. (ASP.NET MVC3)

I'm a little puzzled over the possible cachedependencies in asp.net, and I'm not sure how to use them.

I would like to add items to the HttpRuntime.Cache in a way, that the elements should invalidate if I change other elements in the cache. The dependencies should be defined by the key.

I want a function like this:

public MyObject LoadFromCache(string itemDescriptor, IEnumerable<string> dependencies)
{
    var ret = HttpRuntime.Cache[itemDescriptor] as MyObject;
    if (ret == null)
    {
        ret = LoadFromDataBase(itemDescriptor);

        //this is the part I'm not able to figure out. Adding more than one dependency items.
        var dep = new CacheDependency();
        dependencies.ForEach(o => dep.SomeHowAdd(o));

        HttpRuntime.Cache.Add(
            itemDescriptor, 
            ret, 
            dependencies, 
            System.Web.Caching.Cache.NoAbsoluteExpiration, 
            System.Web.Caching.Cache.NoSlidingExpiration, 
            Caching.CacheItemPriority.Normal, 
            null
        );
    }
    return ret;
}

Help me out on this one.

like image 269
vinczemarton Avatar asked Oct 03 '11 07:10

vinczemarton


1 Answers

I didn't know you could do this, but if you look at the CacheDependency constructor here, you can see that the second parameter is an array of cache keys, so that if any of those cached items change, the whole dependency will be changed and your dependent item will be invalidated as well.

So your code would be something like:

String[] cacheKeys = new string[]{"cacheKey1","cacheKey2"};
var dep = New CacheDependency("", cacheKeys);

HttpRuntime.Cache.Add(itemDescriptor, ret, dep ...);
like image 113
PhilPursglove Avatar answered Oct 21 '22 04:10

PhilPursglove