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

1

6

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.

Psychologism answered 3/10, 2011 at 7:47 Comment(0)
S
7

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 ...);
Sunburn answered 3/10, 2011 at 7:57 Comment(1)
This somehow fails to work. I need to make a few more test cases.Psychologism

© 2022 - 2024 — McMap. All rights reserved.