Dependency Injection — Back to the Basics

DI is a design pattern that ensures that components have their dependencies passed on rather than having to create or obtain them.

Luís Soares
CodeX

--

Image by Spencer via Unsplash Copyright-free

DI is just a fancy name for passing an object its dependencies, i.e., what it needs. A dependency is another component, a function, or simply a value.

“Dependency Injection” is a 25-dollar term for a 5-cent concept. […] Dependency injection means giving an object its instance variables. Really. That’s it. Dependency Injection Demystified

Everything has dependencies, ranging from high-level to low-level:

  • Apps depend upon databases, third-party APIs, the system clock, and configuration values;
  • Use cases need repositories to accomplish their goal (e.g., a use case that transfers money needs a repository);
  • API clients require the server base URL and possibly some configuration values;
  • Entities (domain-centric design) need value objects and primitives to be initialized;
  • Value objects need their raw/primitive values to be initialized (e.g., an email requires a valid string).

Dependencies should be explicitly supplied to the objects’ constructors. Ideally, they…

--

--

Luís Soares
CodeX

I write about automated testing, Lean, TDD, CI/CD, trunk-based dev., user-centric dev, domain-centric arch, ...