Search code examples
c#cachingsingleton

Using singleton for caching


I recently read that singleton is an anti-pattern and should not be used unless it is really needed.

In all our projects, we use the singleton pattern to hold some cache data. For example:

class SomeClass
{
   public SomeClass()
   {
       var somedata = Singleton.Instance.GetSomeData(stringRepresintation); // or like that
       var someData = Singleton.Instance.SomeData;
   }      
}

What is the recommended design to hold that data (static class, or something else)?


Solution

  • Well, you could think of the cache as a dependency - and pass an instance (probably the same instance) into everything which needed it. That's what I'd do in a situation where I was already using dependency injection.

    That would make it easier to test those classes which need the cache - you could create a new cache for each test, and not have to worry about clearing out an existing one. You could also parallelize tests without worrying about two tests messing up each others caches. Additionally, it makes the cache dependency clearer.

    (Whether or not you use an interface to represent the cache as cdhowie suggests is up to you. You don't have to, although it would decouple the classes from their dependencies more if you did. If your cache is very simple and you don't mind using the production implementation in tests, it may not be worth extracting an interface.)