Object-oriented – Initialization of objects in a system using dependency injection

cdependency-injectiondesignobject-oriented

This is a follow up question to the following post: Injecting dependencies (DI) in c++ applications

In a system that uses DI, someone, somewhere should be responsible to create the various objects and "wire" them. I find it difficult to figure out who should do this. I read about one option that it should be the "root class". However, in that case it seems that the root class might be responsible for creating a very large number of objects.

I though of an option to use smaller builder classes that will be used the root class – is that a good way to do it?

Note: I tagged 'C++' in this question because I am developing in C++. I am not sure if it makes any difference to the answer.

Best Answer

It depends on the intended lifetime and ownership of your objects. To construct an object of type C you need an object of type D. Shall this D object have the same lifetime as the C object? Then it makes sense to construct the D object at the same scope where the C object is constructed. Shall the D object live longer than C? Then you should construct it outside before and pass it to the function which constructs C.

Given your objects B, C and D shall have the same lifetime, and that lifetime shall be controlled by an object of type A, it makes sense to let A construct them and "wire" them. If the D object shall live longer, it must be constructed (and destroyed) outside of A.

If you note that A gets too much responsibilities by managing other, dependent objects of B, A might use a "BFactory" class for this purpose, like @gnat suggested as a response to your other question. And if you want to avoid A having to construct that factory, this factory could also be injected into A through an interface "IBFactory".

And if your system gets really large, because you have to not four but 400 classes to manage, then a DI container would be the better choice.