Thread Safety and Scope Management for .NET 4.0 ObjectCache
- Since
MemoryCache.Default
is a singleton, your stateless class doesn't really need to be one. However, that's completely up to you. - You should not need locking around the ObjectCache instance.
- 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. - 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!