views:

401

answers:

1

I had my first go at AppFabric - caching (aka Ms Velocity) today and checked out msdn virtual labs.

https://cmg.vlabcenter.com/default.aspx?moduleid=4d352091-dd7d-4f6c-815c-db2eafe608c7

There is this code sample in it that I dont get. It creates a cache object and stores it in session state. The documentation just says:

We need to store the cache object in Session state and retrieve the same instance of that object each time we need to use it.

Thats not the way I used to use the cache in ASP.NET. What is the reason for this pattern and do I have to use it?

private DataCache GetCache()
{
    DataCache dCache;
    if (Session["dCache"] != null)
    {
        dCache = (DataCache)Session["dCache"];

        if (dCache == null)
            throw new InvalidOperationException("Unable to get or create distributed cache");
    }
    else
    {
        var factory = new DataCacheFactory();
        dCache = factory.GetCache("default");
        Session["dCache"] = dCache;
    }

    return dCache;
}
+1  A: 

I haven't looked at the lab but from what you've put here it looks to me like they've decided that getting a reference to an AppFabric cache (the cache itself, not an object in the cache) from the DataCacheFactory might be a (relatively) expensive operation and so they're getting it from the factory the first time and then caching it in Session state. We never had to do this with the System.Web.Caching.Cache because it's always available from HttpContext.

I can sort of see what they're getting at - this method encapsulates getting the cache object, which might give you slightly cleaner code than having some boilerplate every time you want to use the cache. Of course, it would get pretty confusing if you then started keeping your Session state information in AppFabric as well!

Do you have to use this pattern? No, I don't think so - the alternative is that you create a new DataCache object from the DataCacheFactory every time, which is valid but feels like it would be a bit messier.

PhilPursglove