Hacker News new | ask | show | jobs
by paskozdilar 1535 days ago
> Consistently applied, all construction gets pushed to the entry-point of the program. Congratulations, you've just discovered the so-called "composition root".

I never knew this has an explicit name.

> Turns out computers are really good at topological sorting. So, someone made the computer do it, and we call that a dependency injection container. Tada.

What exactly is a "dependency injection container"? I've searched the internet for the definition, but I've only gotten more confused by all the PHP and C#. You mention topological sorting of dependencies - does that assume a hierarchical object model or can it be used with basically anything?

EDIT:

From what I've read, it appears that a Dependency Injection Container is just an object that:

1) for each dependency type, has a `GetDependency: Type -> Object` method

2) lazily creates dependencies as required by the dependents and the dependency dependencies.

Is this accurate?

2 comments

Beautiful article by Mark Seemann on composition root [1]. Another one on when to use DI container [2].

[1] https://blog.ploeh.dk/2011/07/28/CompositionRoot/

[2] https://blog.ploeh.dk/2012/11/06/WhentouseaDIContainer/

And usually configurable, e.g. for interface Reader use FileReader implementation.