2

So dependency injection then. I understand the concepts (I think!) and the use of containers. What I am failing to understand is the best way to make your DI container available everywhere.

If you have a DB class, do you inject the container into the constructor? So that you can call the DI container methods to create the dependant objects?

Do you do the same for your config class, your mailer class, your logger class and so forth? How do you make your DI container available everywhere?

Help appreciated!

CJD
  • 782
  • 3
  • 10
  • 20

2 Answers2

3

Similar to what CJD said, if your DIC is available everywhere, then it would be more like a Global Registry

In the case of the DB class, if it's dependencies are communicated via type hinting the parameters, defining them externally, in the documentation, or any other acceptable way, then the DIC can inject those dependencies.

Helpful resources:

Anthony Ferra/ircmaxell video on Dependency Injection

Fabian Potencier article about whether you need a DIC

Rob Allen video Introducing Dependency Injection

Stephan Hochdorfer video The 7 Deadly Sins of Dependency Injection

Martin Fowler:

StackOverflow:

Community
  • 1
  • 1
aretecode
  • 334
  • 1
  • 5
1

My understanding is that you don't make it available everywhere. You register all of the objects and their dependencies, and then when you construct the object, the IoC container supplies all of its dependencies (and 2nd-, 3rd-, nth- level dependencies).

So foo needs bar, bar needs baz and qux, and qux needs quux. Foo only needs bar injected, the IoC will take care of the details of supplying bar with its dependencies, and so on.

If foo needs to make more bars later, then it has a dependency on a bar factory, which the IoC can also supply.

error
  • 694
  • 4
  • 14
  • In addition, the DI Container should be used/available only by a framework or other similar infrastructure code, not directly by the other code. This means that your chosen framework must support DI and containers. – MikeSW Feb 05 '15 at 23:17