Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 57 ยท Design Principles

Dependency Inversion and Dependency Injection

Understand the Dependency Inversion Principle, constructor injection and inversion of control, and build a tiny dependency injection container.

The Dependency Inversion Principle (DIP), the "D" in SOLID, has two parts. First, high-level modules should not depend on low-level modules; both should depend on abstractions. Second, abstractions should not depend on details; details should depend on abstractions. In plain words: the important code (your business rules) should not know which database, mail service or file system it talks to. It should only know a small contract that describes what it needs.

Three related terms are easy to mix up, so let us separate them now. Dependency Inversion is the design principle. Inversion of Control (IoC) is the broader idea that a framework or caller decides when your code runs and what it gets, rather than your code controlling everything. Dependency Injection (DI) is a technique that implements the principle: objects receive their collaborators from outside instead of creating them. A DI container is a tool that automates the wiring.

Before and after

Without DIP Order service creates its own MySQL gateway.
With DIP Order service asks for a PaymentGateway contract.
Plug in anything Real gateway in production, a fake in tests.

The arrow of source-code dependency points toward the abstraction.

1 / 2

High-level and low-level modules

A high-level module contains policy: "when an order is placed, charge the customer and send a receipt". A low-level module contains a mechanism: "talk to Stripe", "write a row to MySQL", "send SMTP mail". Policies change for business reasons; mechanisms change for technical ones. When policy code imports mechanism code directly, a change in the mail provider forces edits in your order logic, and you cannot test the order logic without sending real mail.

DIP flips the dependency. The high-level module owns a small abstraction (Notifier, PaymentGateway) shaped by what it needs. The low-level modules implement that abstraction. The source-code arrow, which used to point from policy to mechanism, now points from both toward the abstraction. That is the "inversion".

Here is the problem in code. OrderService creates its own dependencies, so it is welded to them:

Java
class OrderService {
    private final SmtpMailer mailer = new SmtpMailer("smtp.example.com");
    private final MySqlOrderStore store = new MySqlOrderStore();

    void place(Order order) {
        store.save(order);
        mailer.send(order.customerEmail(), "Thanks for your order");
    }
}

You cannot test place without a database and a mail server, and you cannot switch to another store without editing the class. This snippet is read-only; the next section shows the fix in code you can run.

Constructor injection

The simplest form of DI is constructor injection: the class declares what it needs as constructor parameters, and whoever creates it supplies them. The class never calls new on a collaborator.

JS Constructor injection with fakes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The same OrderService class ran twice with completely different collaborators and was never edited. In a statically typed language you would declare the two abstractions as interfaces (OrderStore, Mailer); JavaScript relies on the agreed method names, which is the same idea without the compiler's help.

Other injection styles exist. Setter (property) injection assigns a dependency after construction, which is useful for optional ones but allows half-built objects. Method injection passes a dependency to one method call. Prefer constructor injection for required collaborators: the object is complete the moment it exists, and its needs are visible in one place.

The "interface" in DIP belongs to the client, not to the implementer. OrderService defines what it needs from a mailer; the SMTP class conforms. If the abstraction is designed around the SMTP library's features, you have only added a layer, not inverted anything.

Writing a tiny DI container

Wiring by hand is clear for small programs. With dozens of classes, the "composition root" (the one place that builds the object graph) grows long. A DI container stores recipes for creating objects and builds them on demand, including their dependencies. Here is a minimal one in Node.js. It supports singletons (one shared instance) and transient objects (a new one each time), and it detects circular dependencies.

Node.js A tiny DI container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

This is a stand-in for real frameworks, not a copy of one. Production containers (Spring in Java, Laravel's service container in PHP, dependency-injector or FastAPI's Depends in Python) add type-based auto-wiring, scopes, lifecycle hooks and configuration. The core idea is what you just ran: a map of recipes, and a resolver that builds each object with its own dependencies.

Pitfalls to avoid

  • Passing the container around. If classes receive the container and call resolve themselves, the dependencies are hidden again. This is the Service Locator anti-pattern, covered in Dependency Injection in Practice. Use the container only in the composition root.
  • Interfaces for everything. Not every class needs an abstraction. Create one where there is a real boundary: I/O, time, randomness, third-party services, or places where you expect more than one implementation.
  • Too many constructor parameters. A constructor with eight dependencies usually means the class does too much. Treat it as a hint to split the class, as in the Single Responsibility Principle.
  • Injecting what should be a value. Pass plain data as arguments; inject collaborators that do work.

DIP also connects to the earlier principles. Open/Closed is easier when new behavior is a new implementation of an existing abstraction, and substitution is only safe if each implementation follows Liskov.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the Dependency Inversion Principle say high-level modules should depend on?

    Both high-level and low-level modules should depend on abstractions, so policy code is not tied to mechanism code.
  2. 2. Which statement best describes dependency injection?

    DI means the dependencies are supplied (injected) by the caller or composition root, usually through the constructor.
  3. 3. Why is constructor injection usually preferred for required dependencies?

    With constructor injection there are no half-initialized objects, and the constructor signature documents what the class needs.
  4. 4. What problem appears when classes call container.resolve() themselves?

    Hidden lookups make it unclear what a class needs and make testing harder. Keep the container in the composition root.
  5. 5. In the container example, what does a singleton registration do?

    Singleton scope caches the first instance, so every later resolve returns the same object.

Summary

  • DIP: policy code and detail code both depend on abstractions owned by the policy side.
  • Dependency Injection supplies collaborators from outside; prefer constructor injection.
  • Inversion of Control is the wider idea that something else wires and calls your code.
  • A DI container is a map of recipes plus a resolver; keep it in the composition root.
  • Fakes and spies make tests fast and deterministic.
  • Add abstractions at real boundaries, not everywhere.

Next lesson: DRY, KISS, YAGNI, Law of Demeter and Composition over Inheritance.