Skip to content
jshacks.dev
Patterns

DI Containers in JavaScript: Do You Need One?

A DI container builds your object graph for you. See how one works by writing a tiny one, what it costs and when manual wiring is the better choice.

8 min read
Summarize in AI
Flat illustration of shipping containers stacked on a ship, with the JavaScript, GitHub Actions, Terraform and Kubernetes logos.

A dependency injection container is a registry that knows how to build your objects and their dependencies, so you ask for a UserService and it constructs the logger, the database and the mailer it needs. Frameworks such as NestJS and libraries such as InversifyJS and tsyringe provide one. Most JavaScript programs do not need one, because plain functions and a composition root do the same job in a few lines. This post builds a working container in about thirty lines on Node.js 24 so you can see exactly what it does, shows the manual wiring it replaces, and gives a rule for when the container starts to pay. Every sample prints its output.

The manual version first

Here is an application with four pieces wired by hand.

manual.mjsJavaScript
class Logger {
  info(msg) {
    console.log(`[info] ${msg}`);
  }
}

class Database {
  constructor(logger) {
    this.logger = logger;
  }
  find(id) {
    this.logger.info(`find ${id}`);
    return { id, name: "Ada" };
  }
}

class Mailer {
  constructor(logger) {
    this.logger = logger;
  }
  send(to) {
    this.logger.info(`mail ${to}`);
  }
}

class UserService {
  constructor(db, mailer) {
    this.db = db;
    this.mailer = mailer;
  }
  welcome(id) {
    const user = this.db.find(id);
    this.mailer.send(user.name);
  }
}

const logger = new Logger();
const service = new UserService(new Database(logger), new Mailer(logger));
service.welcome(1);
Text
[info] find 1
[info] mail Ada

The last two lines are the wiring. With four classes it is trivial. With sixty, a composition root becomes long, and adding a dependency to a deep class means editing every place that builds it. That pain is what a container removes.

A container in thirty lines

A container is a map from names to factories, plus a cache so each thing is built once.

container.mjsJavaScript
export class Container {
  #factories = new Map();
  #instances = new Map();

  register(name, factory) {
    this.#factories.set(name, factory);
    return this;
  }

  resolve(name) {
    if (this.#instances.has(name)) return this.#instances.get(name);
    const factory = this.#factories.get(name);
    if (!factory) throw new Error(`No registration for "${name}"`);
    const instance = factory(this);
    this.#instances.set(name, instance);
    return instance;
  }
}

Each factory receives the container, so it can resolve its own dependencies. Now the same application:

with-container.mjsJavaScript
import { Container } from "./container.mjs";

const c = new Container()
  .register("logger", () => new Logger())
  .register("db", (c) => new Database(c.resolve("logger")))
  .register("mailer", (c) => new Mailer(c.resolve("logger")))
  .register("users", (c) => new UserService(c.resolve("db"), c.resolve("mailer")));

c.resolve("users").welcome(1);
console.log(c.resolve("logger") === c.resolve("db").logger);
Text
[info] find 1
[info] mail Ada
true

The final line confirms Database and the container's own logger are the same object, because resolution caches, which is what the word "singleton scope" means. This is the core of every container. The real libraries add features on top: scopes, automatic resolution by type, decorators and lifecycle hooks.

A missing registration fails with a clear message

missing.mjsJavaScript
import { Container } from "./container.mjs";

const c = new Container().register("users", (c) => ({ db: c.resolve("db") }));
try {
  c.resolve("users");
} catch (err) {
  console.log(err.message);
}
Text
No registration for "db"

Note when it fails: at resolution, not at startup. Manual wiring fails earlier, because a typo in an import is a syntax error before the program runs.

Scopes: per application and per request

The cache above is a single scope. Servers need a second: objects that live for one request. A simple way is a child container that inherits registrations and has its own instance cache.

scoped.mjsJavaScript
export class ScopedContainer {
  #factories;
  #instances = new Map();
  #parent;

  constructor(factories = new Map(), parent = null) {
    this.#factories = factories;
    this.#parent = parent;
  }

  register(name, factory, { scope = "singleton" } = {}) {
    this.#factories.set(name, { factory, scope });
    return this;
  }

  createScope() {
    return new ScopedContainer(this.#factories, this);
  }

  resolve(name) {
    const entry = this.#factories.get(name);
    if (!entry) throw new Error(`No registration for "${name}"`);
    const owner = entry.scope === "singleton" && this.#parent ? this.#parent : this;
    if (owner !== this) return owner.resolve(name);
    if (!this.#instances.has(name)) this.#instances.set(name, entry.factory(this));
    return this.#instances.get(name);
  }
}

const app = new ScopedContainer()
  .register("config", () => ({ region: "eu" }))
  .register("requestId", () => Math.random().toString(36).slice(2, 6), { scope: "request" });

const a = app.createScope();
const b = app.createScope();
console.log(a.resolve("config") === b.resolve("config"));
console.log(a.resolve("requestId") === a.resolve("requestId"));
console.log(a.resolve("requestId") === b.resolve("requestId"));
Text
true
true
false

Shared config is one object across scopes, and each scope gets its own requestId. The actual value differs per run, but the comparisons are fixed. Getting scopes right is where homemade containers grow bugs, such as a singleton that captures a request-scoped dependency and keeps it forever. That "captive dependency" mistake is a real reason to use a mature library.

What a container costs

  • Indirection. c.resolve("db") hides which class you get. Following the code means reading registrations.

  • Late failures. Missing registrations surface at runtime, and circular dependencies surface as stack overflows unless the library detects them.

  • Magic. Decorator-and-reflection containers need TypeScript's experimentalDecorators or the newer standard decorators plus metadata, and tie classes to the container's API.

  • Startup and bundle weight. Libraries add code and sometimes reflect-metadata.

A function-based composition root has none of these. Compare the same wiring as plain functions:

composition.mjsJavaScript
function createApp() {
  const logger = new Logger();
  const db = new Database(logger);
  const mailer = new Mailer(logger);
  return { users: new UserService(db, mailer) };
}

createApp().users.welcome(2);
Text
[info] find 2
[info] mail Ada

It is typed, checked by the compiler, and debuggable by reading from top to bottom.

When a container earns its place

A rough rule: consider one when the composition root passes a few hundred lines, when many classes need per-request scoping, or when a framework such as NestJS already provides one and structures your project around it. Below that, manual wiring is clearer. If you only want to reduce typing, split the root into one function per module, as in createBilling(deps), and compose those.

Where the advice stops

A container is not wrong. In a large NestJS application the container is the architecture, and fighting it costs more than it saves. The argument is against adopting one by default in a small Express or script project, where it adds a layer between you and the code. If you cannot say which problem it solves for you today, you do not need it yet.

Circular dependencies

A container cannot build two objects that each need the other from a constructor. With the minimal container above, resolving them recurses until the stack runs out.

cycle.mjsJavaScript
import { Container } from "./container.mjs";

const c = new Container()
  .register("a", (c) => ({ b: c.resolve("b") }))
  .register("b", (c) => ({ a: c.resolve("a") }));

try {
  c.resolve("a");
} catch (err) {
  console.log(err.name, "-", err.message);
}
Text
RangeError - Maximum call stack size exceeded

Better containers detect the cycle and name it. The fix is a design change, not a container feature: extract the shared part into a third object that both depend on, or let one side receive the other through an event or a callback after construction.

Detecting the cycle yourself

Adding detection to the toy container takes a few lines: track names currently being resolved and throw if you meet one again.

detect.mjsJavaScript
export class SafeContainer {
  #factories = new Map();
  #instances = new Map();
  #resolving = [];

  register(name, factory) {
    this.#factories.set(name, factory);
    return this;
  }

  resolve(name) {
    if (this.#instances.has(name)) return this.#instances.get(name);
    if (this.#resolving.includes(name)) {
      throw new Error(`Circular dependency: ${[...this.#resolving, name].join(" -> ")}`);
    }
    this.#resolving.push(name);
    try {
      const instance = this.#factories.get(name)(this);
      this.#instances.set(name, instance);
      return instance;
    } finally {
      this.#resolving.pop();
    }
  }
}

const c = new SafeContainer()
  .register("a", (c) => ({ b: c.resolve("b") }))
  .register("b", (c) => ({ a: c.resolve("a") }));

try {
  c.resolve("a");
} catch (err) {
  console.log(err.message);
}
Text
Circular dependency: a -> b -> a

That message is what you want from any container you adopt. When you evaluate a library, make a deliberate cycle and see what it says.

Testing with a container

Containers make one thing easy: overriding a registration for a test. Register a fake under the same name, and everything that depends on it receives the fake.

override.mjsJavaScript
import { Container } from "./container.mjs";

const c = new Container()
  .register("mailer", () => ({ send: () => "real smtp" }))
  .register("users", (c) => ({ welcome: () => c.resolve("mailer").send() }));

const test = new Container()
  .register("mailer", () => ({ send: () => "fake" }))
  .register("users", (c) => ({ welcome: () => c.resolve("mailer").send() }));

console.log(c.resolve("users").welcome(), test.resolve("users").welcome());
Text
real smtp fake

You pay for that convenience by repeating registrations, which is why real libraries provide child containers and overrides. With manual wiring, the same override is the argument you pass to createApp({ mailer }).

A decision table

SituationBetter choice
Script or small service, under a dozen objectsManual wiring in one function
Express or Fastify app with a few dozen servicesComposition root split per module
NestJS projectThe built-in container, used as intended
Needs request-scoped services in many placesA library with scopes
Library meant to be imported by othersNo container, accept dependencies as arguments

The last row matters for anyone publishing a package. A library that requires its users to adopt a particular container forces that choice on every consumer, while a library that takes plain arguments works with any of them. Ship the arguments and let applications decide how to wire them.

Migrating from a container back to plain wiring

Teams sometimes find a container was adopted too early. The way out is gentle. Pick one leaf service, replace its resolve calls with constructor arguments, and construct it by hand in a new composition function. Leave the container in place for everything else. Repeat for each service until the container is empty, then delete it. Because the services already take their dependencies through constructors, the classes themselves do not change, and only the wiring moves. That is a good sign for the original design: if removing a container is this easy, the code never depended on it.

Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.