Inyección de Dependencias

DI · Inversión de Control

Escrito por Darjus Kazakevic · revisado el

Give a component its collaborators; do not let it create them.

If a use case calls new PgOrders(db), a Postgres repository, it depends on a driver, a connection string and a running database, in every test too. Dependency injection removes that line. The use case declares what it needs as an interface and receives an instance from outside.

One place, the composition root (usually the entry point, such as index.ts), picks the real implementations and wires them together. A DI container is one way to do this. In code built from small functions, a function that takes its dependencies is often enough.

En esencia — Pass a component its dependencies from outside, so it depends only on interfaces and one composition root chooses the real implementations.

Cuándo recurrir a él

Recurre a él cuando

  • Enforcing a dependency rule: clean, hexagonal or onion layers
  • Testing the domain without a database or network
  • Code that reads the clock, random numbers or new ids

Reconsidéralo cuando

  • Pure functions and value objects, which have no collaborators
  • Stable helpers with no side effects, like a string formatter
  • Small scripts where the extra layer costs more than it gives

The moving parts

The port
An interface owned by the code that needs it, in that code's words: OrderRepository, not PostgresClient. The name should still fit after you replace the technology behind it.
The injection
How the instance arrives: as a constructor argument or a function parameter. Both make the dependency visible and required, so the object cannot exist without it.
The composition root
The one place, at the entry point, where concrete implementations are chosen and connected. It is the only file that imports both the domain and the infrastructure.

Applying it well

Create concrete classes in one place only
Only the composition root writes new PgOrders(db). Every other file receives interfaces. A single new PgOrders() anywhere else breaks the dependency rule, and no test will notice.
Let the consumer define the interface
The port belongs to the code that needs it, in its own words. An interface copied from an existing class, with the same methods and an “I” prefix, inverts nothing.
Inject through the constructor or a function
Dependencies passed at creation are visible and required. A curried function, (deps) => (input) => result, needs no container at all. Setters and service locators allow objects that cannot do their job.
Inject time and randomness too
Clocks, id generators and random sources are dependencies. Injecting them makes a use case give the same result in every test run, without freezing global time.

Errores habituales

  • A service locator passed around as a dependency, which hides the real dependencies again.
  • Container decorators on domain classes, so the model depends on the framework.
  • Interfaces extracted from implementations instead of defined by the code that uses them.
  • Interfaces with exactly one implementation and no fake, added only out of habit.