Dependency Injection — Design Patterns

Dependency Injection: a function or object receives its dependencies from outside (createBooking({ store, notifier }), new UserService(repo)) instead of…

How do you test a Kancil Courier booking without sending a real SMS to a customer? As long as createBooking fetches its own SMS sender, you can't.

Dependency Injection (DI) means a function or object receives its dependencies from outside, instead of creating or fetching them itself. A dependency is another object it needs to do its job: a store, a message sender, a tracking number counter. Picture a cook in a restaurant kitchen. The ingredients are prepared and brought to the station; the cook doesn't run to the market in the middle of cooking. When a new cook is tested, practice ingredients are brought instead, and the recipe stays exactly the same. A cook who goes shopping for every order can't be tested without a market.

The problem: a createBooking that fetches for itself

The old version of Kancil Courier's booking core fetched everything it needs itself, including TrackingCounter from the Singleton lesson:

function createBooking() {
  return {
    book({ recipient, phone, service, kg }) {
      if (!Object.hasOwn(RATES, service)) throw new Error("Unknown service: " + service)
      const trackingNo = TrackingCounter.getInstance().next() // singleton
      const shipment = { trackingNo, recipient, phone, service, kg, cost: kg * RATES[service], status: "picked_up" }
      shipmentDb.set(trackingNo, shipment) // a global Map
      smsAdapter.notify(phone, trackingNo + " picked up, shipping $" + shipment.cost) // the production adapter
      return shipment
    },
  }
}

The test tries to hand it an in-memory store and a fake notifier, createBooking({ store: createInMemoryStore(), notifier: fake }), but JavaScript quietly ignores arguments nobody asked for. Two tests, each booking one parcel and expecting KCL-0001:

SMS gateway → 07700900123: KCL-0001 picked up, shipping $36
fail: express 2 kg: KCL-0001 $36, messages recorded 0
SMS gateway → 07700900456: KCL-0002 picked up, shipping $30
fail: regular 3 kg: KCL-0001 $30, got KCL-0002 $30

Two real SMS left the app from a test, the fake recorded 0 messages, and the second test got KCL-0002 because the singleton carried the count over from the first test. From its line alone, createBooking() doesn't say it needs a counter, a database and an SMS vendor.

DI: the dependencies are passed in from outside

You already wrote DI in the Ports & Adapters lesson, you just didn't name it:

function createBooking({ store, notifier }) {
  return {
    book({ recipient, phone, service, kg }) {
      if (!Object.hasOwn(RATES, service)) throw new Error("Unknown service: " + service)
      const trackingNo = store.nextTrackingNo()
      const shipment = { trackingNo, recipient, phone, service, kg, cost: kg * RATES[service], status: "picked_up" }
      store.save(shipment)
      notifier.notify(phone, trackingNo + " picked up, shipping $" + shipment.cost)
      return shipment
    },
  }
}

// main.js: the only place that assembles
const booking = createBooking({ store: createApiStore(api), notifier: smsAdapter })

// booking.test.js: the test assembles its own version
function setup() {
  const sent = []
  const booking = createBooking({
    store: createInMemoryStore(), // a fresh tracking counter for every test
    notifier: { notify: (phone, message) => sent.push(message) }, // fake: only records
  })
  return { booking, sent }
}
// pass: express 2 kg: KCL-0001 $36
// pass: regular 3 kg: KCL-0001 $30

The name Dependency Injection comes from Martin Fowler's 2004 article "Inversion of Control Containers and the Dependency Injection pattern". Inversion of Control means control is turned around: it's not createBooking that looks for its dependencies, it's the caller that provides them.

Three ways to pass them in

class BookingService {
  constructor(store, notifier) { // 1. constructor injection: required, passed in at creation
    this.store = store
    this.notifier = notifier
  }
  setLogger(logger) { // 2. setter injection: optional, plugged in afterwards
    this.logger = logger
  }
  printLabel(shipment, printer) { // 3. method injection: changes with every call
    printer.print(shipment.trackingNo + " " + shipment.recipient)
  }
}

Container: automatic assembly, still in main.js

When there are dozens of dependencies that depend on each other, assembling by hand in main.js gets long. A DI container keeps a recipe for making each dependency, then assembles them on request:

function createContainer() {
  const factories = new Map()
  const instances = new Map()
  return {
    register(name, factory) { factories.set(name, factory) },
    resolve(name) {
      if (!instances.has(name)) instances.set(name, factories.get(name)(this))
      return instances.get(name)
    },
  }
}

// main.js
const container = createContainer()
container.register("store", () => createApiStore(api))
container.register("notifier", () => smsAdapter)
container.register("booking", (c) => createBooking({ store: c.resolve("store"), notifier: c.resolve("notifier") }))
const booking = container.resolve("booking")

Service locator: a hidden dependency

A service locator also has register and get, but it is called from inside the core:

const locator = {
  services: new Map(),
  register(name, service) {
    this.services.set(name, service)
  },
  get(name) {
    if (!this.services.has(name)) throw new Error("Service not registered: " + name)
    return this.services.get(name)
  },
}
// bootstrap.js: runs when the app loads, and during tests too
locator.register("store", createApiStore(api))
locator.register("notifier", smsAdapter)

createBooking() goes back to having no parameters, and book fetches const store = locator.get("store") and const notifier = locator.get("notifier") itself; the rest is the same as the DI version. The test registers locator.register("store", createInMemoryStore()) but forgets the notifier, then books two parcels. Take a guess first: does the test pass or fail, and how many real SMS go out?

The result: pass twice, 2 of 2, and 2 real SMS sent (SMS gateway → 07700900123: KCL-0001 picked up, shipping $36, then one more to 07700900456). The locator still holds smsAdapter from bootstrap, and nothing in createBooking() says it needs a notifier. In the DI version, a forgotten notifier can't slip through: the test stops with TypeError: Cannot read properties of undefined (reading 'notify') and 0 SMS are sent.

Fowler (2004) compares the two approaches; Mark Seemann (2010) calls the service locator an anti-pattern because its dependencies are hidden from the signature, so they're hard to see and hard to swap for fakes in tests. What tells them apart is who calls it: a container called only in main.js is DI, a container passed into createBooking and resolved there is a service locator again.

💡 In frameworks: Laravel and Angular

Exercise: UserService with constructor injection

The exercise uses the class version:

The starter registers Budi and Ani, so the console shows Budi, Ani, Unknown (for id 999), then 2 (the size of repo.users).

⚠️ Dependencies that get fetched from inside again

TL;DR: Dependency Injection: a function or object receives its dependencies from outside (createBooking({ store, notifier }), new UserService(repo)) instead of creating or fetching them itself. Its needs show in its signature, main.js assembles the production version, and tests assemble their own with an in-memory store and a fake: 2 of 2 pass, 0 real SMS. Constructor injection for required dependencies, setter injection for optional ones, method injection for ones that change with every call. The TrackingCounter.getInstance() singleton is replaced by a store made once in main.js, so every test can start at KCL-0001. A container (Laravel, Angular, or a tiny createContainer) only automates the assembly and is still called in main.js. A service locator (locator.get("notifier") inside the core) hides dependencies: a test that forgets to register a fake still passes while sending 2 real SMS.

⚡ A core that fetches for itself

Guess first: createBooking() fetches TrackingCounter, a global database and smsAdapter by itself. A test hands it an in-memory store and a fake notifier. What happens?

The arguments are quietly ignored. Two real SMS leave the app from the test, the fake records 0 messages, and the second test gets KCL-0002 because the singleton carried the count over from the first.

Meaning: From its line alone, createBooking() doesn't say it needs a counter, a database and an SMS vendor.

⚡ Dependencies passed in from outside

Write:

function createBooking({ store, notifier }) {
  return {
    book({ recipient, phone, service, kg }) {
      if (!Object.hasOwn(RATES, service)) throw new Error("Unknown service: " + service)
      const trackingNo = store.nextTrackingNo()
      const shipment = { trackingNo, recipient, phone, service, kg, cost: kg * RATES[service], status: "picked_up" }
      store.save(shipment)
      notifier.notify(phone, trackingNo + " picked up, shipping $" + shipment.cost)
      return shipment
    },
  }
}

Meaning: Dependency Injection: an object receives its dependencies from outside, it doesn't create them itself inside. main.js assembles the production version, tests assemble their own with an in-memory store and a fake: 2 of 2 pass, 0 real SMS.

⚡ A service locator hides dependencies

Meaning: A container called only in main.js is still DI. When locator.get("notifier") is called from inside the core, the dependencies are hidden from the signature, and a test that forgets to register a fake still passes while sending real SMS.

What you will learn