# Dependency Injection Options for Node.js Dependency injection (DI) is a way to provide a class with the collaborators it needs instead of having the class construct those collaborators itself. In a Node.js application, DI can make services easier to test, replace, configure, and reason about as the application grows. A service should focus on application behavior: ```ts export class OrdersService { constructor( private readonly orders: OrderRepository, private readonly payments: PaymentGateway, private readonly mailer: Mailer, ) {} async placeOrder(input: PlaceOrderInput): Promise { const order = await this.orders.create(input); await this.payments.authorize(order.total); await this.mailer.sendOrderConfirmation(order); return order; } } ``` The composition root decides which implementations to provide: ```ts const ordersService = new OrdersService( new PostgresOrderRepository(), new StripePaymentGateway(), new SmtpMailer(), ); ``` For tests, the same service can receive fakes: ```ts const ordersService = new OrdersService( new InMemoryOrderRepository(), new FakePaymentGateway(), new RecordingMailer(), ); ``` ## What dependency injection solves DI helps with: - **Testability:** replace databases, APIs, queues, clocks, and file systems with fakes. - **Dependency inversion:** application code depends on interfaces or contracts rather than infrastructure classes. - **Configuration:** select implementations for development, testing, staging, and production. - **Lifetimes:** control whether an object is a singleton, request-scoped, transient, or manually managed. - **Composition:** centralize construction of a complex object graph. - **Swappability:** change an implementation without changing the service that uses it. - **Separation of concerns:** keep business logic separate from object construction and infrastructure setup. ## Important Node.js DI concepts ### Composition root The composition root is the part of the application that assembles the object graph. It is commonly located in: - `app.ts` - `server.ts` - `bootstrap.ts` - `container.ts` - A framework module or application startup function Keep construction in the composition root rather than spreading `new ConcreteClass()` throughout services and route handlers. ### Dependency contract A dependency contract can be a TypeScript interface, abstract class, function type, or token-backed interface: ```ts export interface PaymentGateway { authorize(amount: number): Promise<{ transactionId: string }>; } ``` TypeScript interfaces disappear at runtime, so decorator-based containers usually require explicit tokens for interface dependencies. ### Lifetimes Common lifetimes are: - **Singleton:** one instance for the process. Suitable for stateless configuration, immutable clients, and connection pools. - **Request-scoped:** one instance for an HTTP request or message-processing scope. Suitable for request context, unit-of-work state, or authorization context. - **Transient:** a new instance for every resolution. Suitable for lightweight, stateful, or short-lived objects. A singleton must not retain request-specific state. Conversely, a request-scoped dependency must not accidentally be captured by a process-wide singleton. ### Lazy factories A factory is useful when a dependency must be resolved at the moment it is used: ```ts export type Clock = () => Date; const clock: Clock = () => new Date(); ``` Factories are also helpful for request-scoped objects, conditional implementations, and dependencies that should not be initialized during application startup. ## Five practical DI options for Node.js ### 1. Hand-rolled registry **Dependency:** None A small module owns construction and exposes functions or factories for retrieving dependencies. ```ts type AppDependencies = { orders(): OrderRepository; payments(): PaymentGateway; mailer(): Mailer; }; let factory: () => AppDependencies = () => ({ orders: () => new PostgresOrderRepository(), payments: () => new StripePaymentGateway(), mailer: () => new SmtpMailer(), }); export const dependencies = (): AppDependencies => factory(); export const useDependencies = (next: () => AppDependencies): void => { factory = next; }; ``` **Strengths** - No package or decorator overhead - Easy to understand and debug - Simple test override mechanism - Lazy factories can preserve request-specific behavior - Appropriate for a small service graph **Tradeoffs** - Dependencies are implicit if services call the registry directly - It is effectively a service locator - No built-in lifetime management or dependency-graph validation - The registry can become a central module with too much responsibility **Best use:** Start here when the application is small and the team wants explicit, low-risk wiring without adopting a container. --- ### 2. Awilix **Dependency:** [`awilix`](https://github.com/jeffijoe/awilix) Awilix is a convention-based container that does not require decorators or `reflect-metadata`. It supports explicit lifetimes: - `SINGLETON` - `SCOPED` - `TRANSIENT` Example registration: ```ts import { asClass, asFunction, createContainer, Lifetime, } from "awilix"; export const container = createContainer({ injectionMode: "CLASSIC", }); container.register({ ordersService: asClass(OrdersService, { lifetime: Lifetime.SCOPED, }), orderRepository: asClass(PostgresOrderRepository, { lifetime: Lifetime.SCOPED, }), paymentGateway: asClass(StripePaymentGateway, { lifetime: Lifetime.SINGLETON, }), mailer: asFunction(() => new SmtpMailer(), { lifetime: Lifetime.SINGLETON, }), }); ``` An Express application can create a scope for each request: ```ts app.use((req, res, next) => { req.scope = container.createScope(); res.on("finish", () => req.scope.dispose()); next(); }); ``` **Strengths** - Native request scopes - No decorator ceremony - Explicit lifetimes and registration - Easy replacement of production dependencies with test fakes - Good balance between features and complexity - Supports both class and factory registrations **Tradeoffs** - Adds a dependency - `CLASSIC` mode resolves constructor parameters by name and can be stringly typed - Existing direct `new Service()` call sites need to become container resolutions - `PROXY` mode or typed registrations may be needed to reduce name-based coupling **Best use:** The strongest general-purpose choice when a Node.js application needs a real container without decorator-heavy code. --- ### 3. tsyringe **Dependencies:** [`tsyringe`](https://github.com/microsoft/tsyringe) and [`reflect-metadata`](https://github.com/rbuckton/reflect-metadata) Tsyringe is Microsoft's lightweight decorator-based container. Classes use `@injectable()`, and interface dependencies require explicit runtime tokens because TypeScript interfaces do not exist at runtime. ```ts import "reflect-metadata"; import { inject, injectable } from "tsyringe"; export const TOKENS = { OrderRepository: Symbol("OrderRepository"), PaymentGateway: Symbol("PaymentGateway"), Mailer: Symbol("Mailer"), }; @injectable() export class OrdersService { constructor( @inject(TOKENS.OrderRepository) private readonly orders: OrderRepository, @inject(TOKENS.PaymentGateway) private readonly payments: PaymentGateway, @inject(TOKENS.Mailer) private readonly mailer: Mailer, ) {} } ``` A child container can be created for request-level overrides: ```ts app.use((req, _res, next) => { req.container = rootContainer.createChildContainer(); next(); }); ``` **Strengths** - Familiar constructor injection - Small and focused container - Explicit tokens preserve interface boundaries - Child containers support request-level overrides - Works well in TypeScript projects already using decorators **Tradeoffs** - Requires decorators and `reflect-metadata` - Interface dependencies require token definitions and `@inject(...)` annotations - More boilerplate than Awilix or a hand-rolled provider - Direct `new OrdersService()` calls must become container resolutions - Request-scoped resources require deliberate child-container setup **Best use:** Teams that prefer decorator-based constructor injection and want a lightweight container rather than a full framework. --- ### 4. InversifyJS **Dependency:** [`inversify`](https://github.com/inversify/InversifyJS) InversifyJS is a full-featured decorator-based IoC container. It uses explicit bindings, tokens, modules, and lifecycle configuration: ```ts container.bind(TOKENS.OrderRepository) .to(PostgresOrderRepository) .inRequestScope(); container.bind(TOKENS.PaymentGateway) .to(StripePaymentGateway) .inSingletonScope(); ``` In practice, a project normally maintains: - Symbol or token definitions - `@injectable()` annotations - Binding modules - Container setup and middleware integration - Explicit scope decisions - A convention for composing application modules **Strengths** - Powerful binding model - Contextual bindings and middleware/interception support - Suitable for large, complex object graphs - Strong separation between contracts and implementations - Flexible lifecycle and resolution behavior **Tradeoffs** - Highest ceremony of the five choices - Decorators and metadata add build/runtime complexity - Request scope requires deliberate configuration and integration - More files and conventions to maintain - Often overkill for a small or medium Node.js application **Best use:** Large applications that need contextual bindings, advanced interception, modular containers, or a highly explicit dependency graph. --- ### 5. `node-dependency-injection` (NDI) **Dependencies:** [`node-dependency-injection`](https://github.com/zazoomauro/node-dependency-injection) and optionally [`node-dependency-injection-express-middleware`](https://www.npmjs.com/package/node-dependency-injection-express-middleware) NDI is a Symfony-inspired container based on `ContainerBuilder`, `Definition`, and `Reference`. Definitions are compiled at startup and can be configured in YAML, JSON, or JavaScript. Notable features include: - Explicit service definitions - Type-based autowiring - Service tags - Keyed services - Lazy services - Compiler passes - Conditional registration - A `ndi` inspection and validation CLI - Express middleware integration Example definition: ```ts const serviceDefinition = new Definition(OrdersService, [ new Reference("orders.repository"), new Reference("payments.gateway"), new Reference("mailer"), ]); serviceDefinition.shared = false; container.setDefinition("orders.service", serviceDefinition); await container.compile(); ``` `shared = false` is important when a service or one of its dependencies contains request-specific state. A shared service can otherwise capture state from the first request that resolves it. **Strengths** - No decorators or `reflect-metadata` - Inspectable and auditable configuration - YAML/JSON configuration makes wiring explicit - Conditional registration supports environment-specific implementations - Compiler validation can catch service-graph problems at startup - Familiar to teams with Symfony-style dependency injection experience **Tradeoffs** - No native request scope; `shared = false` and lazy factories must be used consistently - Easy to accidentally create a shared service with stale request state - Autowiring cannot infer TypeScript interfaces without explicit definitions or bindings - Source scanning adds development startup overhead - Production autowiring may require a generated service-configuration artifact - Smaller ecosystem than Awilix, tsyringe, and InversifyJS - Express integration requires an additional package **Best use:** Applications that value declarative, inspectable configuration, conditional service wiring, and compile-time validation. ## Comparison | Option | Extra dependencies | Decorators | Request-scope support | Main advantage | Main risk | Best fit | | --- | --- | --- | --- | --- | --- | --- | | Hand-rolled registry | None | No | Lazy factories | Smallest change and easiest testing | Implicit dependencies/service locator | Small codebase | | Awilix | `awilix` | No | Native `createScope()` | Best balance of lifetimes and simplicity | Name-based resolution in some modes | Most Node.js applications needing a container | | tsyringe | `tsyringe`, `reflect-metadata` | Yes | Child containers | Familiar constructor injection | Token and decorator boilerplate | Decorator-oriented teams | | InversifyJS | `inversify`, metadata tooling | Yes | Requires deliberate setup | Full-featured contextual bindings | Highest ceremony and complexity | Large service graphs | | `node-dependency-injection` | NDI plus optional Express package | No | No native scope; use `shared: false` | Declarative and inspectable wiring | Easy to create shared request-state bugs | Symfony-style configuration | ## Recommended adoption path ### Phase 1: explicit constructor dependencies Start with normal constructor injection and a small composition root: ```ts const service = new OrdersService( new PostgresOrderRepository(), new StripePaymentGateway(), new SmtpMailer(), ); ``` This gives the application most of the testability benefits of DI without adding a container. ### Phase 2: use factories for dynamic or scoped dependencies Use a factory when a dependency must be created per request, selected by configuration, or resolved only when needed: ```ts type RepositoryFactory = () => OrderRepository; export class OrdersService { constructor(private readonly getOrders: RepositoryFactory) {} list() { return this.getOrders().findAll(); } } ``` ### Phase 3: introduce a container only when needed If the object graph becomes large enough to justify a container: 1. Prefer **Awilix** for request scopes and low ceremony. 2. Consider **NDI** when declarative configuration and conditional wiring are priorities. 3. Consider **tsyringe** when the team strongly prefers decorators. 4. Use **InversifyJS** when advanced binding and contextual features justify its complexity. ## Common mistakes to avoid - Constructing infrastructure dependencies inside business services - Hiding every dependency behind a global service locator - Registering request-specific state as a process singleton - Mutating a global container with per-request values under concurrent load - Mixing production and test registrations without a reset strategy - Using decorators when simple constructor injection is sufficient - Introducing a container before the application has a real composition problem - Forgetting to dispose request scopes or other resources - Allowing the container to become the only place where application behavior is understandable ## Using dependency injection with MikroORM These DI approaches can be used with MikroORM by injecting repositories, repository factories, or an ORM-neutral repository provider into application services. The important rule is to resolve request-scoped EntityManagers lazily and never capture a request-dependent EntityManager in a process-wide singleton. For the MikroORM-specific repository architecture, request context, transactions, criteria DSL, testing strategy, and PostgreSQL example, see [MikroORM for Node.js](./Node-ORM-MikroOrm.md). ## Related pages - [MikroORM for Node.js](./Node-ORM-MikroOrm.md) - [Node ORMs](./Node-ORMs.md) - [Repository interfaces](./Repository-Interfaces.md) - [Repositories](./Repositories.md)