Best practice when using Azure AppFabric Caching Service?
Asked Answered
E

1

4

I have successfully started using Azure AppFabric Caching Service, but I' not sure what the best practice way of creating the DataCacheFactory object is. Now I'm creating it for every call into the cache, but apparently this is not the ideal way of doing it...

Some advise call for a Singleton. But I'm not sure I understand how this would be implemented (not the actual Singleton class, but how to tie it all together).

Today I have a CacheProvider class that is created for me using Ninject where I can do Get/Put/Remove operations. For each of these methods I create the DataCacheFactory object and then call .GetDefaultCache() to get the DataCache object, where I call Put/Get/Remove respectively. I do this in a single method that looks like this:

private T Cache<T>(Func<DataCache, T> cacheAction)
{
    using (DataCacheFactory dataCacheFactory = new DataCacheFactory())
    {
        DataCache dataCache = dataCacheFactory.GetDefaultCache();
        return cacheAction(dataCache);
    }
}

I'm now pretty sure that this is not-so-clever-idea, I should instead be getting the DataCache object via a Singleton where the DataCacheFactory object is just created once. BUT how will that object survive between requests? And how does that work with > 1 instance on Azure?

Hope all this makes sense and that somebody with more experience than me (3 hours) can help me out.

Elative answered 23/2, 2012 at 13:12 Comment(1)
See method CacheUtil.GetCache from hanselman.com/blog/…Naxos
S
6

Singleton objects live at the application scope. Simply declare your private DataCache object on a global static level, provide a property Get that instantiates the object if it is null or returns the object if it is not null.

This way, you will be paying the cost of instrumenting configuration and connection of the cache only once per application recycle.

Each instance will instantiate its own DataCache object and it is ok.

The actual data, where the cache is stored is not stored on your local machine's memory, but in Azure's dedicated cache servers that are distributed and mega-fast.

Sabaean answered 23/2, 2012 at 17:54 Comment(3)
I'd add that each instance of the DataCacheFactory counts as one of the connections in your cache quota, so using a singleton is a really good idea. Also the data might live in memory if you've enabled local caching.Throve
Sounds good. I have already changed my code to this approach and it appears to work as expected. Too bad Microsoft doesn't show this in the docs, would have been so much easier to implement it correct then... Thanx!Elative
In an Azure MVC 3 webrole, would that mean decalring it in the Global.asax.cs file?Enallage

© 2022 - 2024 — McMap. All rights reserved.