Skip to content

Repository files navigation

Node Dependency Injection

Node Dependency Injection

Modern TypeScript DI without decorators and without reflect-metadata.
Autowiring, validation, and container compilation for maintainable Node.js services.
Inspired by the battle-tested Symfony DI container.
node-di.dev

Npm Version Build Status Code Coverage Npm Downloads Known Vulnerabilities License


Why Node Dependency Injection?

Managing dependencies manually leads to tightly coupled, hard-to-test code. Node Dependency Injection gives you a powerful, flexible IoC container that wires your application together β€” keeping your classes clean, your tests simple, and your architecture solid.

If you are comparing options in 2026, the core value is simple: TypeScript autowiring by class, without decorators, without runtime metadata hacks, with compile-time style validation workflows.


✨ Features

πŸ”„ Autowire β€” zero-config DI for TypeScript πŸ“ Config files β€” YAML, JSON or JS
🏭 Factory pattern β€” flexible service creation 🏷️ Service tagging β€” group & inject by tag
πŸ’€ Lazy services β€” instantiate only when needed 🎨 Decorators β€” wrap services transparently
⚑ Compiler passes β€” transform the container at build time πŸ”’ Private services β€” encapsulate internals
🌳 Parent / Abstract services β€” share config via inheritance 🧩 Non-shared services β€” new instance per call
🌿 Environment parameters β€” %env(VAR)% support πŸ—‘οΈ Deprecation warnings β€” mark services as deprecated
πŸ“¦ Express middleware β€” first-class web framework support πŸ–₯️ CLI β€” inspect & validate your container
πŸ”€ Conditional services β€” register services based on env or other services πŸ—οΈ Keyed services β€” named strategy pattern with registerKeyed
πŸ”— Autowire + Keyed β€” inject keyed services via parameter binds

πŸ“Š Why choose NDI over Awilix, InversifyJS or tsyringe?

The goal is not to attack alternatives. This table explains the concrete trade-offs and where NDI is opinionated.

Feature node-dependency-injection InversifyJS tsyringe Awilix
Config files (YAML / JSON / JS) βœ… Native ⚠️ Programmatic-first ⚠️ Programmatic-first ⚠️ Programmatic-first
TypeScript autowire without decorators βœ… Native ❌ ❌ ❌
Keyed services (named strategy groups) βœ… Native ⚠️ Via custom patterns ⚠️ Via tokens/patterns ⚠️ Via aliases/patterns
Conditional service registration βœ… Native ⚠️ Manual logic ⚠️ Manual logic ⚠️ Manual logic
Compiler passes / compile-time transforms βœ… Native ❌ ❌ ❌
Service tags and tagged lookup βœ… Native ⚠️ Manual metadata patterns ⚠️ Manual token patterns ⚠️ Naming/registration patterns
Private services βœ… Native ⚠️ Container conventions ⚠️ Container conventions ⚠️ Container conventions
CLI container inspection / validation βœ… Native (ndi) ❌ ❌ ❌
Parent / abstract definitions βœ… Native ⚠️ Composition-based ⚠️ Composition-based ⚠️ Composition-based
Lazy services βœ… Native βœ… ⚠️ Partial patterns ⚠️ Partial patterns

Legend: βœ… built-in, ⚠️ possible with custom conventions or extra setup, ❌ not available as a first-class feature.


πŸš€ Installation

Website: node-di.dev

npm install --save node-dependency-injection

🏁 Quick Start

Start with class-based autowiring (the default recommendation):

import { Autowire, ContainerBuilder } from 'node-dependency-injection'
import UserService from '@src/service/UserService'

const container = new ContainerBuilder(false, '/path/to/src')
const autowire = new Autowire(container)

await autowire.process()
await container.compile()

const userService = container.get(UserService)

No decorators. No tokens. No reflect-metadata.

Prefer explicit IDs and programmatic registration? You can still do that:

import { ContainerBuilder } from 'node-dependency-injection'
import Mailer from './services/Mailer'
import ExampleService from './services/ExampleService'

const container = new ContainerBuilder()

container.register('service.example', ExampleService)
container.register('service.mailer', Mailer).addArgument('service.example')

await container.compile()

const mailer = container.get('service.mailer')

πŸ”„ Autowire (TypeScript)

Zero-configuration dependency injection β€” NDI reads your TypeScript type annotations and wires everything automatically:

import { ContainerBuilder, Autowire } from 'node-dependency-injection'

const container = new ContainerBuilder(false, '/path/to/src')
const autowire = new Autowire(container)
await autowire.process()
await container.compile()

// Retrieve by class β€” no string IDs needed
import SomeService from '@src/service/SomeService'
const service = container.get(SomeService)

// Or retrieve by ID with an explicit type
const typedService = container.get<SomeService>('service.some')

Production tip: dump the autowired config to a YAML file and load it directly in prod β€” no TypeScript scanning overhead.

if (process.env.NODE_ENV === 'development') {
  const autowire = new Autowire(container)
  autowire.serviceFile = new ServiceFile('/dist/services.yaml')
  await autowire.process()
} else {
  const loader = new YamlFileLoader(container)
  await loader.load('/dist/services.yaml')
}
await container.compile()

The generated services.yaml uses human-readable service IDs derived from the file path relative to your source root (e.g. Service/Mailer), making it easy to review, audit, and debug your application's service graph:

# services.yaml (human-readable β€” default since v4.0)
services:
  Service/Mailer:
    class: /Service/Mailer
    arguments:
      - '@Service/Transport'
  Service/Transport:
    class: /Service/Transport
    arguments: []

Service ID strategy

Strategy Default Service ID example Description
readable βœ… v4.0+ Service/Mailer Path relative to defaultDir, extension stripped
legacy v3.x U2VydmljZS9NYWlsZXI= Base64-encoded absolute path

To opt back in to the legacy strategy (e.g. for gradual migration):

const autowire = new Autowire(container)
autowire.makeIdLegacy() // switch back to base64-encoded IDs

🏷️ Tagged Services

Tags classify services into reusable plural collections. Tag attributes remain application-owned metadata until a consumer explicitly gives an attribute meaning.

NDI supports two tagged injection forms. The existing !tagged form remains unchanged for compatibility, while @tagged(...) adds Symfony-style collection projection with priority ordering and optional indexing.

services:
  handler.fast:
    class: './handlers/FastHandler'
    tags:
      - name: app.handler
        attributes:
          priority: 20
          key: fast

  handler.fallback:
    class: './handlers/FallbackHandler'
    tags:
      - name: app.handler
        attributes:
          priority: 0
          key: fallback

  handler.runner:
    class: './HandlerRunner'
    arguments:
      - '@tagged(app.handler)'
Form Result Ordering Attribute semantics
!tagged app.handler Array Definition order Attributes are ignored
@tagged(app.handler) Array Integer priority descending; definition order breaks ties priority controls ordering
@tagged(app.handler, key) Map Same priority ordering key supplies each map key; service id is the fallback

The indexed form can use any tag attribute name, not only key:

arguments:
  - '@tagged(app.handler, name)'

If a service declares the same tag more than once, unindexed projection includes that service once and uses the first tag occurrence for priority. Indexed projection can expose separate entries for repeated tag occurrences when they provide different indexes, matching Symfony tagged-iterator behavior.

Programmatic registration uses the same metadata:

import { ContainerBuilder, TaggedReference } from 'node-dependency-injection'

const container = new ContainerBuilder()
container.register('handler.fast', FastHandler)
  .addTag('app.handler', new Map([
    ['priority', 20],
    ['key', 'fast']
  ]))

container.register('runner', HandlerRunner)
  .addArgument(new TaggedReference('app.handler', 'key'))

Use !tagged when you need the historical definition-order behavior. Use @tagged(...) when the collection itself needs ordering or keyed projection.


πŸ—οΈ Keyed Services

Keyed services let you register multiple implementations of the same interface under a named group, then retrieve a specific one by key or inject the entire group as a Map.

Programmatic API

import { ContainerBuilder, KeyedReference, KeyedGroupReference } from 'node-dependency-injection'
import StripePayment from './payments/StripePayment'
import PaypalPayment from './payments/PaypalPayment'
import CheckoutService from './CheckoutService'
import PaymentRouter from './PaymentRouter'

const container = new ContainerBuilder()

// Register implementations under the 'payment' group
container.registerKeyed('payment', 'stripe', StripePayment).setDefault(true)
container.registerKeyed('payment', 'paypal', PaypalPayment)

// Inject a specific key
container.register('checkout', CheckoutService)
  .addArgument(new KeyedReference('payment', 'stripe'))

// Inject the full group as a Map<key, instance>
container.register('payment.router', PaymentRouter)
  .addArgument(new KeyedGroupReference('payment'))

// Retrieve by key or get the default
const stripe = container.getKeyed('payment', 'stripe')
const defaultPayment = container.getKeyed('payment')          // returns the .setDefault(true) one
const allPayments = container.getKeyedGroup('payment')        // Map { 'stripe' => …, 'paypal' => … }

YAML configuration

services:
  payment.stripe:
    class: 'payments/StripePayment'
    keyed:
      group: payment
      key: stripe
      default: true

  payment.paypal:
    class: 'payments/PaypalPayment'
    keyed:
      group: payment
      key: paypal

  checkout:
    class: 'CheckoutService'
    arguments: ['@keyed(payment, stripe)']

  payment.router:
    class: 'PaymentRouter'
    arguments: ['@keyed_group(payment)']

Autowire integration

When using Autowire you can inject keyed services into typed constructor parameters by registering a bind whose name matches the parameter name:

// TypeScript service
export default class CheckoutService {
  constructor(private readonly payment: IPaymentService) {}
}

export default class PaymentRouter {
  constructor(private readonly payments: Map<string, IPaymentService>) {}
}
container.registerKeyed('payment', 'stripe', StripePaymentService)
container.registerKeyed('payment', 'paypal', PaypalPaymentService)

// The bind name must match the constructor parameter name exactly
container.addBind('payment', new KeyedReference('payment', 'stripe'))
container.addBind('payments', new KeyedGroupReference('payment'))

const autowire = new Autowire(container)
await autowire.process()
await container.compile()

// container.get(CheckoutService).payment  β†’ StripePaymentService
// container.get(PaymentRouter).payments   β†’ Map { 'stripe' => …, 'paypal' => … }

Note: binds take priority over type-based resolution. The same mechanism works for scalar values β€” container.addBind('apiKey', '%env(API_KEY)%') β€” so keyed service binds fit naturally into the existing bind API.


πŸ“ Configuration Files

Prefer declarative config? Use YAML, JSON or JS:

# services.yaml
services:
  service.example:
    class: 'services/ExampleService'

  service.mailer:
    class: 'services/Mailer'
    arguments: ['@service.example']
import { ContainerBuilder, YamlFileLoader } from 'node-dependency-injection'

const container = new ContainerBuilder()
const loader = new YamlFileLoader(container)
await loader.load('/path/to/services.yaml')
await container.compile()

const mailer = container.get('service.mailer')

πŸ”€ Conditional Services

Register services only when specific conditions are met β€” evaluated at compile() time.

import { ContainerBuilder, Condition } from 'node-dependency-injection'

const container = new ContainerBuilder()

// Register only when an environment variable is set
container.register('cache.redis', RedisCache)
  .setCondition(Condition.envExists('REDIS_URL'))

// Fallback: register only when another service was NOT registered (TryAdd)
container.register('cache.memory', InMemoryCache)
  .whenMissing('cache.redis')

// Register only when a sibling service IS registered
container.register('metrics', Prometheus)
  .whenServiceExists('http.server')

// Combine conditions
container.register('feature.x', FeatureX)
  .setCondition(Condition.all(
    Condition.envEquals('NODE_ENV', 'production'),
    Condition.envExists('FEATURE_X_ENABLED')
  ))

await container.compile()

The same conditions are available declaratively in YAML:

services:
  cache.redis:
    class: 'services/cache/RedisCache'
    when:
      env_exists: REDIS_URL

  cache.memory:
    class: 'services/cache/InMemoryCache'
    when:
      missing: cache.redis

  metrics.prometheus:
    class: 'services/metrics/Prometheus'
    when:
      service_exists: http.server

  logger.verbose:
    class: 'services/logger/VerboseLogger'
    when:
      env_equals: { var: LOG_LEVEL, value: debug }

See the Conditional Services wiki page for the full API reference and advanced usage.


πŸ“¦ Ecosystem

Express Middleware

Use NDI seamlessly with Express β€” retrieve the container directly from any request:

npm install --save node-dependency-injection-express-middleware
import NDIMiddleware from 'node-dependency-injection-express-middleware'
import express from 'express'

const app = express()
app.use(new NDIMiddleware({ serviceFilePath: 'services.yaml' }).middleware())

Express Middleware Documentation

CLI

Inspect and validate your container from the command line:

# Validate a config file
ndi config:check /path/to/services.yaml

# Inspect a specific service
ndi container:service /path/to/services.yaml service.mailer

πŸ“– Documentation

The full documentation lives in the project wiki, including guides on:


🀝 Contributing

Contributions are welcome! Please read the contribution guide before submitting a pull request.


πŸ™ Credits

Inspired by the Symfony Dependency Injection component β€” a special thanks to the Symfony team for their outstanding work.


MIT License  ·  Made with ❀️ by @zazoomauro

About

The NodeDependencyInjection component allows you to standarize and centralize the way objects are constructed in your application.

Topics

Resources

Contributing

Stars

298 stars

Watchers

5 watching

Forks

Releases

Packages

Used by

Contributors

Languages