Thread Safety and Scope Management for .NET 4.0 ObjectCache Thread Safety and Scope Management for .NET 4.0 ObjectCache asp.net asp.net

Thread Safety and Scope Management for .NET 4.0 ObjectCache


  1. Since MemoryCache.Default is a singleton, your stateless class doesn't really need to be one. However, that's completely up to you.
  2. You should not need locking around the ObjectCache instance.
  3. No, and No. Making it static doesn't provide any value. Indicating it's a singleton in StructureMap makes GetInstance<>() always return the same object anyways.
  4. The real value of wrapping 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!