Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 57 ยท Architectural and Modern Patterns

Dependency Injection, Service Locator and Plugin Architectures

Wire objects with a composition root, see why the Service Locator hides dependencies, build a plugin registry, and test with fakes and spies.

The lesson on Dependency Inversion and Dependency Injection explained the principle and built a small container. This lesson is about living with it: where the wiring goes in a real program, why the Service Locator looks like DI but quietly undoes its benefits, how plugin architectures let other people add features without touching your code, and how fakes make tests fast.

Everything here runs as plain Node.js. Real frameworks (Spring, Laravel's container, ASP.NET Core, NestJS) automate the wiring, but the ideas are the same as the code you will read below.

Where wiring lives

Composition root One place builds the object graph.
Nowhere else Business classes never call new on collaborators.
At startup Wire once, then run.
1 / 2

The composition root

A composition root is the single place, usually near the program's entry point, where objects are created and connected. Every other class just declares what it needs in its constructor. This keeps all knowledge of concrete classes in one file, so changing the mail provider or the database is a one-line edit there.

flowchart TD
    M["main() composition root"] --> S["OrderService"]
    M --> R["SqlOrderRepository"]
    M --> N["SmtpNotifier"]
    S --> R
    S --> N

Only main() knows the concrete classes. OrderService sees two small contracts.

Notice what the root is not: it is not a global object that the rest of the code reaches into. It builds things and hands them over, then gets out of the way.

The Service Locator and why it hurts

A Service Locator is a registry that classes query for what they need: Locator.get("mailer"). It feels convenient, because constructors stay short, but the dependencies are now hidden inside method bodies. The next TryIt compares the two styles for the same class.

Node.js Injection versus Service Locator

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.

The problems with the locator:

  • Hidden dependencies. You cannot tell what LocatorInvoiceService needs without reading its body. Adding a new dependency does not break any caller, which sounds nice but means a missing registration shows up at run time in production, not at startup or compile time.
  • Global mutable state. Tests share the registry, so they interfere with each other unless carefully reset.
  • Coupling to the locator. Every class now depends on the locator class, which is exactly the kind of dependency the principle tries to remove.

There are some fair uses: a framework's plugin loader, a legacy codebase where you cannot change constructors yet, or a factory that must pick a service by name at run time. Even then, keep the lookup in the composition root or in a factory, and pass the result into your classes.

Plugin architectures

A plugin architecture lets other code extend a program without modifying it. The host defines an extension point (a small contract), keeps a registry of implementations, and calls whatever has been registered. It is the Open/Closed Principle at program scale: editors with extensions, build tools, payment providers, import/export formats.

Key design decisions:

  • A narrow contract. The smaller the interface, the easier it is for plugins to implement and for you to keep stable.
  • Identification. Each plugin has a unique name, so a configuration file can enable "csv" or "json".
  • Registration. Plugins call registry.register(plugin) when loaded, or the host discovers them (files in a folder, an installed package).
  • Failure isolation. One broken plugin should not take down the host.
  • Versioning. Changing the contract breaks every plugin. Evolve it carefully.
Node.js A plugin registry for exporters

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.

The host never mentions markdown. Real plugin systems add loading from disk or packages (Node's dynamic import(), Java's ServiceLoader, Python entry points), but the registry and contract at the center look just like this. Because the registry here is a stand-in with plugins defined in the same file, there is no sandboxing; in a real system untrusted plugins need isolation and permission checks.

Testing with fakes

With injection, tests pass in simple replacements. Know the vocabulary, which people use loosely:

  • A stub returns canned answers (a clock that always says the same date).
  • A fake is a working lightweight version (an in-memory repository).
  • A spy records how it was called, so you can assert afterwards.
  • A mock is pre-programmed with expectations that fail the test if not met.
Node.js Testing a service with stub, fake and spy

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.

The test runs in a fraction of a millisecond, needs no mail server and no database, and does not depend on today's date. That payoff, more than any container, is the reason to inject dependencies.

Practical guidelines

  • Inject things that do I/O or vary: databases, HTTP clients, mail, the clock, random numbers, the file system.
  • Do not inject plain values or simple helper functions that never change, such as a string formatter.
  • If a constructor takes more than four or five collaborators, the class probably has too many responsibilities; revisit Single Responsibility.
  • Use the container (if you use one at all) only in the composition root.
  • Prefer small interfaces owned by the client, in line with Interface Segregation.

Limitations of Dependency Injection

DI is not free. It adds complexity: a composition root or container must be written and understood, and with a container, wiring errors move from compile time to start-up or runtime. It can add a small runtime overhead (reflection, object graph creation), usually negligible next to I/O. Constructors with many parameters are a smell that a class does too much, and DI makes that visible rather than fixing it. For tiny scripts or classes with a single stable dependency, a plain constructor call is simpler. The benefits (loose coupling, easier testing, easier swapping and collaboration on separate modules) outweigh these costs in most applications that live longer than a few weeks.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is a composition root?

    The composition root builds concrete objects and passes them to the classes that need them, so the rest of the code knows only abstractions.
  2. 2. What is the main drawback of the Service Locator?

    You cannot see what a class needs from its constructor, and the global registry is shared state that tests must manage.
  3. 3. Which describes a plugin architecture?

    A narrow contract plus a registry lets new behavior be added from outside, which applies the Open/Closed Principle at program scale.
  4. 4. In test vocabulary, what is a spy?

    A spy records calls (such as the mails sent). A stub returns canned values and a fake is a lightweight working version.
  5. 5. Which dependency is the best candidate to inject?

    Time varies and makes tests non-deterministic. Injecting a clock lets tests fix the date. Pure helpers and constants need no injection.

Summary

  • Build the object graph in one composition root; business classes never create their own collaborators.
  • A Service Locator hides dependencies and adds global state; use it only at the edges, if at all.
  • Plugin architectures combine a small extension contract with a registry, validation and failure isolation.
  • Fakes, stubs and spies replace slow or unpredictable collaborators in tests.
  • Inject I/O and sources of variation (clock, randomness, network), not plain values.
  • Many constructor parameters point to a class with too many responsibilities.

Next lesson: Patterns Across Languages: Java, C++, Python and JavaScript.