C# – Dependency Injection vs Singleton Pattern

cdependency-injection

I just read documentation and tutorial about dependency injection (DI) and the singleton pattern (SP). Everybody seems to says DP is bad and DI is the way to do it. Tutorials about dependency injection use some framework like Autofac or Ninject. They also all explain DI don't need a framework, container. I understand.

Actually DI is not complicate. You create an interface then you pass the implementation of your interface to the constructor.

But always come the moment where they explain that with Autofac or Ninject or other container you must define the lifetime of you class. So you have this line

kernel.Bind<MyFacade>.To<MyFacade>().InSingletonScope(); 

And again yes. DI is simple but in the simple version of DI there is no Singleton. So when you want to use DI for singleton behavior you must use a container, right? So at the end the container is just managing the single stuff for you, right?

So DI is not something we should oppose to SP.
DI with container is something I can oppose to SP.

So at the end why I should not use SP by myself but trust a library to do it? What is the difference between DI using container with single scope and SP?

Best Answer

You're correct that the idea of DI is to be able to rely on an abstraction (interface) rather than a concrete implementation, but that is only one piece of the puzzle. You still need to instantiate the actual object somewhere else, before passing in to a constructor or injecting it. The bigger part here is how you create that instance. Since simply new-ing up the object still keeps you tied to that specific implementation, it's recommended instead to use a pattern such as a factory. Using a DI container just makes it easier and allows us to not reinvent the wheel, but of course you can do whatever suits your needs best.

Now, if you only have a couple classes or a small project, then maybe just using the singleton pattern on your own is perfectly acceptable. It all comes down to preference.

Related Topic