Is dependency injection useful in C++

Marcel Hoffmann picture Marcel Hoffmann · Mar 31, 2015 · Viewed 43.1k times · Source

C# uses Dependency Injection (DI) a lot to have a lossless and testable platform. For this, I need an interface and maybe a DI or Inversion of Control (IoC) container for resolving my instances.

But how do you do this in C++? I've read a little bit about this, and it seems that dependency injection in C++ isn't as big a topic as in C#. In C++ you use a reference to an object - this is the way to use DI in C++, right?

If my theory with references are correct, is there something like a container where I can resolve all the references? In C# I have a "bad class/bad project/assembly" which registers all my instances into a static container at the program start. Then, in every class, I'm able to instance the static container and can resolving a specific instance, is this possible in C++?

Are you using Dependency Injection (or whatever it is called) in C++? If yes, how you're use it? Are there similarities to C#?

Answer

utnapistim picture utnapistim · Mar 31, 2015

For this, I need an interface and maybe a container for resolving my instances. But how you do this in C++?

In the same way. The difference is that where you "program to an interface" in C#, you "program to a base class" in C++. Additionally, you have extra tools in C++ that you do not have in C# (for example, policy-based templates implement dependency injection chosen at compilation time).

In C++ you're use a reference to an object, this is the way to use DI in C++, right?

No; this is not the way to use DI, this is a way to use DI in C++.

Also consider:

  • use a pointer to an object (or smart pointer, depending on the case)
  • use a template argument for a policy (for an example, see std::default_delete use in smart pointers)
  • use lambda calcullus with injected functors/predicates.

In C# I've a "bad class/bad project/assembly" which register all my instance into a static container at the program start.

If I understand correctly, you set all your data in this static container and use it all over the application. If this is the case, then you do not use dependency injection correctly, because this breaks Demeter's Law.

is this possible in C++?

Yes, it is perfectly possible (but you shouldn't do it, due to it breaking Demeter's law). Have a look at boost::any (this will allow you to store heterogenous objects in a container, similar to storing objects by object reference in C#).

Are you using dependency injection or whatever it is called in C++?

Yes (and it is called dependency injection :) ).

If yes, how you're use it?

As I described above (policy template arguments, injected functors and predicates as reusable components, injecting objects by reference, pointer smart pointer or value).