liveBook · Manning

Dependency injection

As explained in Grokking Software Architecture

Injection is the process of providing a dependency to the object that needs it.

Dependency injection provides an object with the other objects it needs, instead of having it create them itself. This loosens coupling and makes dependencies easier to replace. section 2.4.3

A report generator shows the difference:

  • Tightly coupled: the generator creates its own database connection, so tests depend on a real database. section 2.4.3
  • Loosely coupled: the generator receives a database connection in its constructor, so tests can provide a fake. section 2.4.3

Test with a fake dependency

Pass an object with a getData method that returns three test rows to the report generator. Its report logic can then be checked without connecting to a real database. section 2.4.3

Figure 2.7 Loose coupling replaces hardcoded connections with a flexible "Socket" (Interface). This allows the Report Generator to stay stable while you swap in a Fake DB for fast testing or a Real DB for production without changing the core code.

The socket-and-plug illustration shows how a report generator can use a fake database for tests or a real one in production. section 2.4.3

The same pattern lets an OrderService receive a logger that meets a contract rather than calling a specific static logger. In a larger refactor, injected dependencies can help separate responsibilities and improve testability, though that choice takes more upfront work. section 4.5.2 section 3.5.2

How Grokking Software Architecture covers it

How deep it goes
Defines injection and works through constructor-based database and logger examples, including a fake-dependency test.
Examples
Uses report-generator tests with real and fake databases, plus an OrderService that receives a logger.
What you can do after
Apply it by passing a fake database or logger into a component instead of hard-coding that dependency.
How it connects
Connects dependency injection with loose coupling, abstractions, Dependency Inversion, testability, and Separation of Concerns.

Also explained in

Compare how 28 books explain dependency injection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Software Architecture. The section links point to the parts of the book it draws on.