I'm using the new .NET 4.0 Caching API, ObjectCache. I've asked a few questions on this area the last few days, and i've hinted to this issue - but thought it's worthwhile to break it out into it's own question.
Because the class is abstract and all the methods are virtual, this means we can create our own custom cache providers.
According to MSDN, ObjectCache
does not have to be a singleton, and you can create multiple instances of it in your application.
But to me, this sounds like we need to manage the instantiation and lifetime of this object as well?
I have an ASP.NET MVC 3 Web Application, with StructureMap as my dependency injection container.
I want to have a single, shared cache for my entire web application.
So, i create a very simple class which wraps the ObjectCache
class, and provides the unboxing in the methods implementation.
The class takes an instance of ObjectCache
in the ctor, and sets this to a private static instance of the cache, which the methods (Add, Get, etc) work off.
E.g
public class CacheManager
{
private static ObjectCache _cache;
public CacheManager(ObjectCache cache)
{
_cache = cache;
}
// Add, Get, Remove methods work off _cache instance.
}
Now, here's my DI registry:
For<CacheManager>().Singleton().Use<CacheManager>().Ctor<ObjectCache>("cache").Is(MemoryCache.Default);
In english: When something requests a CacheManager instance, use a singleton instance, and set the ObjectCache parameter to be a MemoryCache instance.
So there's what i have, now the questions:
ObjectCache
, does this class need to be a singleton?ObjectCache
is thread-safe, but now that i'm using a singleton, do i need any type of locking to keep the thread safety?ObjectCache
in my wrapper class need to be static? Does the class itself need to be static?I have not been able to find a decent blog/article on .NET ObjectCache in ASP.NET Web Applications, hence my confusion.
I'm use to using HttpContext.Current.Cache
(which is static) and not care about lifetime management for the cache.
MemoryCache.Default
is a singleton, your stateless class doesn't really need to be one. However, that's completely up to you. GetInstance<>()
always return the same object anyways. ObjectCache
would to be abstract the cache implementation so you can change it or mock it. Without an interface this becomes less useful. An example implementation below...
public interface ICacheManager
{
// add, get, remove, etc
}
public class CacheManager : ICacheManager
{
private static ObjectCache _cache;
public CacheManager(ObjectCache cache)
{
_cache = cache;
}
// Add, Get, Remove methods work off _cache instance.
}
Then...
For<ICacheManager>()
.Singleton()
.Use<CacheManager>();
For<ObjectCache>()
.Use(MemoryCache.Default);
If you want to change you cache provider that is still an ObjectCache
in the future, then it's easy to adjust.
I hope this helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With