Dependency Injection vs Singleton – Different Concepts?

Architecturecsingleton

I've been hearing about using the dependency injection over Singleton for my colleague. I still can't make out if it they are two orthogonal patterns which can be replaced with one another? Or is DI a method to make the Singleton pattern testable?

Please take a look at the following code snippet.

    IMathFace obj = Singleton.Instance;

    SingletonConsumer singConsumer = new SingletonConsumer(obj);

    singConsumer.ConsumerAdd(10,20);

The SingletonConsumer is accepting a parameter of type IMathFace. Instead of accessing the singleton class internally, SingletonConsumer will get the singleton instance passed by the caller. Is this a good example of consuming singleton class via dependency injection?

Best Answer

I think he meant that you should use dependency injection to inject a single instance of the service, instead of using the classical Singleton implementation with a static accessor MySingleton.Instance.

public class MySingleton
{
    public static MySingleton Instance{get{...}};
}

With the classical singleton implementation all your code depends on that service being a singleton. You basically hardcode that assumption into consuming code whenever you use MySingleton.Instance.

On the other hand with DI you get an instance of the service passed into your constructor, and store it. That there is only a single instance of this service is an implementation detail. You can easily change it to give the consuming code a different instance. That way you have some class/interface which happens to be implemented by a single instance, instead of enforcing that there is only one instance.

This is useful if you for example want a mock implementation of the service for testing, or if different parts of the program need different configurations of that service.