Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 57 ยท Design Principles

Inversion of Control and IoC Containers

Learn what Inversion of Control means, how it differs from Dependency Injection, the Service Locator and DIP, and build a small IoC container with lifetimes and cycle detection.

Four terms get mixed up constantly: Inversion of Control, Dependency Inversion, Dependency Injection and Service Locator. People use them as if they were synonyms, and then argue in code reviews about nothing. They are related but different things, at different levels. This lesson separates them, then looks inside an IoC container (the thing Spring, ASP.NET Core, Laravel, NestJS and Angular all ship) by building a small one.

Inversion of Control: who calls whom

In ordinary code, your code is in charge. Your main calls a library, which returns, and your code calls the next one. With Inversion of Control (IoC), you hand over control: you write pieces, and a framework decides when to call them.

You have used it already:

  • You pass a callback to a button, and the browser decides when to call it.
  • You write a controller method, and the web framework decides when a request reaches it.
  • You pass a comparator to sort, and sort calls it when it wants.
  • You write @Test methods, and the test runner finds and runs them.

This is the Hollywood Principle: "Don't call us, we'll call you." A library is something you call. A framework is something that calls you. IoC is the general idea, and it has many forms: callbacks, Template Method, Observer, events, plugins, and dependency injection.

Dependency Injection is one kind of IoC

A class has dependencies, such as a mailer or a clock. Without IoC it creates them itself (new SmtpMailer()), so it controls which mailer it uses. With Dependency Injection (DI), something outside creates the dependency and gives it to the class, usually through the constructor. The control over "which implementation" is inverted: the class no longer decides.

JavaScript
// Not inverted: the class chooses and builds its own dependency.
class Welcome { constructor() { this.mailer = new SmtpMailer(); } }

// Inverted: the caller decides what to pass in.
class Welcome { constructor(mailer) { this.mailer = mailer; } }

How the terms fit together

Term What it is Level
Dependency Inversion Principle (the D in SOLID) A design rule: high-level code depends on abstractions, not concrete classes Principle
Inversion of Control The general idea that a framework or caller controls flow or creation Concept
Dependency Injection A technique: dependencies are passed in from outside Pattern
IoC container (DI container) A tool that builds objects and injects their dependencies automatically Tool
Service Locator A registry the class asks for dependencies; the class stays in charge of fetching Alternative pattern

The Dependency Inversion Principle says what a good design looks like (see Dependency Inversion). Injection is how you achieve it. A container automates the injection. A locator looks similar from the outside but hides dependencies inside method bodies, as shown in Dependency Injection in Practice.

flowchart TD
    DIP["Principle:<br/>depend on abstractions (DIP)"] --> DI["Technique:<br/>Dependency Injection"]
    DI --> C["Tool:<br/>IoC container"]
    IOC["Concept: Inversion of Control"] --> DI
    IOC --> CB["Callbacks, events,<br/>Template Method, plugins"]

IoC is the broad idea; Dependency Injection is one form of it; a container automates DI; DIP is the design rule that motivates it.

What an IoC container does

By hand, you wire everything in one place, the composition root:

JavaScript
const db = new Database(config);
const mailer = new SmtpMailer(config);
const users = new UserRepository(db);
const welcome = new WelcomeService(users, mailer);

This is fine for ten classes. For hundreds it becomes a long file that you must keep in the right order. A container takes over that bookkeeping. It does three jobs:

  1. Register: you tell it how to produce each service, or which concrete class stands behind each abstraction.
  2. Resolve: when you ask for a service, it builds it, first resolving everything that service needs, recursively.
  3. Manage lifetimes: it decides whether to reuse an instance or create a fresh one.

Common lifetimes:

  • Singleton: one instance for the whole container. Good for config, caches and stateless services.
  • Transient: a new instance every time. Good for lightweight, stateful objects.
  • Scoped: one instance per scope, such as one per web request. Good for a database session or the current user.

Building a tiny container

The container below registers each service with a factory that receives the container itself. The factory states what it needs by calling container.resolve(...). It also detects circular dependencies and reports an understandable error.

Node.js A small IoC 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.

Notice what the output shows. The mailer and repository are built once, on the first resolve("welcome"), not at registration, because the container builds services lazily. welcome is transient, so each resolve makes a new WelcomeService, but it receives the same shared mailer. The application classes (WelcomeService, UserRepository) contain no container code at all, so you can build them by hand in a unit test. Swapping the real mailer for a fake is a one-line change in the composition root.

Failing early, with a clear message

A container that fails on a missing registration or a circular dependency saves hours of confusion.

Node.js Missing services and circular dependencies

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.

A cycle usually means two classes know too much about each other. Break it by extracting the shared part into a third class, by depending on an interface or event instead, or, as a last resort, by injecting a lazy factory function.

How real containers go further

The mini container uses manual factories, which is how Laravel's service container, Pimple or Guice modules often work. Many frameworks add automatic wiring (autowiring): the container reads the constructor's parameter types and builds them itself, so new WelcomeService(users, mailer) needs no registration beyond mapping interfaces to implementations. Java's Spring and CDI do this with reflection and annotations, .NET's Microsoft.Extensions.DependencyInjection by constructor type, and Laravel with PHP type hints. TypeScript frameworks (NestJS, Angular) rely on decorator metadata. JavaScript has no runtime parameter types, so plain JS containers use explicit factories or a list of dependency names.

Real containers also add scopes (per request), decorators, configuration profiles, startup validation of the whole graph, and disposal of resources when the scope ends.

Using a container well

  • Use it only at the edge. Resolve the top-level object once, in main or a framework entry point. Everything below receives its dependencies through constructors.
  • Never pass the container around. A class that receives the container and calls resolve is a Service Locator wearing a costume. It has the same hidden dependencies and the same test pain.
  • Prefer constructor injection. It makes requirements visible and objects always valid after construction.
  • Keep lifetimes honest. A singleton must not hold a scoped or transient service that it expects to be fresh. This "captive dependency" bug gives one user another user's data.
  • You may not need one. Small programs are fine with hand-written wiring in a composition root, and doing it by hand first teaches you what a container saves you from.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does Inversion of Control mean in general?

    IoC is the broad 'don't call us, we'll call you' idea. Callbacks, events, Template Method and dependency injection are all forms of it.
  2. 2. How are Dependency Injection and IoC related?

    DI inverts control over creating dependencies. IoC is the wider concept that also includes callbacks and framework-called code.
  3. 3. Which describes a Service Locator, as opposed to Dependency Injection?

    With a locator, the class pulls dependencies itself and its constructor says nothing about them. With injection they are pushed in and visible.
  4. 4. A container resolves 'welcome' twice and gets two different WelcomeService objects, but both share one mailer. Which lifetimes explain this?

    A transient service is built fresh each time, while a singleton is built once and reused.
  5. 5. What is a 'captive dependency' bug?

    A long-lived object that captures a short-lived one keeps it alive, which can leak one user's data into other requests.

Summary

  • Inversion of Control means a framework or caller controls the flow ("don't call us, we'll call you"); callbacks, events and Template Method are examples.
  • Dependency Injection is one form of IoC where dependencies are passed in; the Dependency Inversion Principle is the design rule behind it.
  • An IoC container registers how to build services, resolves them recursively and manages lifetimes (singleton, transient, scoped).
  • Good containers fail early on missing registrations and circular dependencies.
  • Use the container at the edge only; passing it around turns it into a Service Locator.
  • Beware captive dependencies, and remember that hand-written wiring is enough for small programs.

Next lesson: Beyond SOLID.