Skip to content
jshacks.dev
Patterns

How to Use tsyringe for Dependency Injection

Learn tsyringe dependency injection in TypeScript: injectable and inject decorators, register and resolve, lifecycles, child containers and tests with fakes.

7 min read
Summarize in AI
Flat illustration of a service container binding interfaces to classes, with the JavaScript, TypeScript, Vite, npm and Node.js logos.

tsyringe is Microsoft's lightweight dependency injection container for TypeScript. It resolves constructor dependencies using decorators and the type metadata the compiler emits, so a class that lists what it needs in its constructor can be created with a single container.resolve(Class) call. This guide covers tsyringe 4 with TypeScript 5.9 on Node.js 24: setup, the @injectable, @inject and @singleton decorators, registering interfaces, lifecycles, child containers for request scopes, and tests that swap in fakes. Check the project's release notes for newer major versions before upgrading.

What tsyringe gives you

The container's job is to take a class and construct it with its dependencies already built. For classes whose constructor parameters are other classes, tsyringe needs no configuration at all: it reads the parameter types from emitted metadata and resolves each. For interfaces, which have no run-time existence, you register a token and say which implementation to use. It is smaller than InversifyJS and has fewer binding types, which is an advantage if you want constructor injection and lifetimes and little else.

Setup

Install the library and the metadata polyfill.

installShell
npm install tsyringe reflect-metadata

The compiler must emit decorator metadata.

tsconfig.jsonJSON
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "strict": true
  }
}

Import reflect-metadata once, as the first line of the program's entry file, before any file that uses a decorator is loaded: import "reflect-metadata";. Decorators and parameter metadata are not erasable syntax, so Node.js cannot run these files by stripping types. Build with tsc, or run through tsx.

Step 1: classes that depend on classes

The simplest case needs one decorator. @injectable() tells tsyringe to record the constructor's parameter types.

classes.tsTypeScript
import "reflect-metadata";
import { injectable } from "tsyringe";

@injectable()
export class UserRepository {
  private readonly users = new Map<number, string>([[1, "Ada"], [2, "Lin"]]);

  findName(id: number): string | undefined {
    return this.users.get(id);
  }
}

@injectable()
export class GreetingService {
  constructor(private readonly repository: UserRepository) {}

  greet(id: number): string {
    return `Hello, ${this.repository.findName(id) ?? "stranger"}`;
  }
}
resolve.tsTypeScript
import "reflect-metadata";
import { container } from "tsyringe";
import { GreetingService } from "./classes.ts";

const service = container.resolve(GreetingService);
console.log(service.greet(1));
console.log(service.greet(7));
Text
Hello, Ada
Hello, stranger

container.resolve(GreetingService) saw that the constructor takes a UserRepository, constructed one, and passed it in. Nothing was registered, because for a concrete class the type is its own token. By default each resolve creates a new instance of every class in the graph.

Step 2: interfaces need tokens

An interface disappears when TypeScript compiles, so there is nothing for the container to look up. Register an implementation under a string, a Symbol or a class token, and use @inject(token) where it is needed.

logger.tsTypeScript
import "reflect-metadata";
import { container, inject, injectable } from "tsyringe";

export interface Logger {
  info(message: string): void;
}

@injectable()
class ConsoleLogger implements Logger {
  info(message: string): void {
    console.log(`[log] ${message}`);
  }
}

container.register<Logger>("Logger", { useClass: ConsoleLogger });

@injectable()
export class AuditService {
  constructor(@inject("Logger") private readonly logger: Logger) {}

  record(action: string): void {
    this.logger.info(`audit: ${action}`);
  }
}

container.resolve(AuditService).record("login");
Text
[log] audit: login

The register call maps the "Logger" token to the ConsoleLogger class. @inject("Logger") on the constructor parameter tells the container which token to use, since the interface type cannot be read at run time. Strings work, but a shared Symbol or a constant avoids typos, and the TypeScript generic on register<Logger> documents the type.

Besides useClass, a registration can be useValue, for a ready-made object, useFactory, for a function that builds the value with access to the container, or useToken, an alias to another token.

providers.tsTypeScript
import "reflect-metadata";
import { container } from "tsyringe";

container.register("apiUrl", { useValue: "https://api.example.com" });
container.register("clock", { useFactory: () => ({ now: () => "2026-11-20T10:00:00Z" }) });
container.register("endpoint", { useFactory: (c) => `${c.resolve<string>("apiUrl")}/v1` });

console.log(container.resolve<string>("apiUrl"));
console.log(container.resolve<{ now(): string }>("clock").now());
console.log(container.resolve<string>("endpoint"));
Text
https://api.example.com
2026-11-20T10:00:00Z
https://api.example.com/v1

The factory receives the container as its argument, so one registration can build its value from others, as endpoint does.

Step 3: lifecycles

By default a registration is transient: every resolve builds a new instance. For shared services, choose a lifecycle.

lifecycle.tsTypeScript
import "reflect-metadata";
import { container, injectable, Lifecycle, singleton } from "tsyringe";

@singleton()
class Config {
  readonly createdAt = Math.random();
}

@injectable()
class Transient {}

class Shared {}
container.register("shared", { useClass: Shared }, { lifecycle: Lifecycle.Singleton });

console.log(container.resolve(Config) === container.resolve(Config));
console.log(container.resolve(Transient) === container.resolve(Transient));
console.log(container.resolve("shared") === container.resolve("shared"));
Text
true
false
true

@singleton() registers the class as a singleton and makes it injectable, in one decorator. A registration with Lifecycle.Singleton does the same for a token. The other lifecycles are Lifecycle.ResolutionScoped, which gives one instance per resolve call and its dependency graph, and Lifecycle.ContainerScoped, which gives one instance per container, including child containers. The value of createdAt is random and differs between runs, so the example compares object identity, which is stable.

Step 4: child containers for request scopes

A web server wants some objects to live for one request, such as the current user. Child containers provide that: a child inherits the parent's registrations and can add or override its own.

request.tsTypeScript
import "reflect-metadata";
import { container, inject, injectable, Lifecycle } from "tsyringe";

@injectable()
class RequestLogger {
  constructor(@inject("requestId") private readonly requestId: string) {}

  info(message: string): string {
    return `[${this.requestId}] ${message}`;
  }
}

container.register(RequestLogger, { useClass: RequestLogger }, { lifecycle: Lifecycle.ContainerScoped });

function handleRequest(requestId: string): string {
  const child = container.createChildContainer();
  child.registerInstance("requestId", requestId);
  return child.resolve(RequestLogger).info("handling");
}

console.log(handleRequest("req-1"));
console.log(handleRequest("req-2"));
Text
[req-1] handling
[req-2] handling

Each request creates a child container, registers its own requestId and resolves the logger through it. Because the logger is container-scoped, each child gets its own instance, and the two requests do not share one. The parent holds the registration, and the children supply per-request values. This is how you get request scope without a framework: one child container per request, discarded when the request ends.

Step 5: tests with fakes

A test registers a fake under the token, resolves the class under test and asserts on what the fake recorded. Using a child container keeps the override from leaking into other tests.

audit.test.tsTypeScript
import "reflect-metadata";
import assert from "node:assert/strict";
import { test } from "node:test";
import { container } from "tsyringe";
import { AuditService } from "./logger.ts";

test("audit records the action through the logger", () => {
  const lines: string[] = [];
  const child = container.createChildContainer();
  child.registerInstance("Logger", { info: (message: string) => void lines.push(message) });

  child.resolve(AuditService).record("logout");

  assert.deepEqual(lines, ["audit: logout"]);
});
Text
✔ audit records the action through the logger (1.3ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0

registerInstance binds an existing object, which is the natural way to install a fake. The child's registration shadows the parent's "Logger" token, and the parent keeps the real one. For tests that use the global container, container.clearInstances() drops cached singletons, and container.reset() removes all registrations.

Pitfalls

Forgetting the polyfill import. Without import "reflect-metadata" at the top of the entry file, tsyringe throws an error saying the polyfill is required. Because decorators run at class definition time, the import must come before any decorated class is loaded, and a different import order can break it.

**Missing @injectable().** A class with constructor parameters and no decorator has no recorded metadata, and tsyringe cannot tell what to inject. It reports that the type has missing or incorrect parameter information.

Circular imports. If two files import each other, one class can be undefined when the decorator metadata is read, and the container sees an undefined dependency. Break the cycle, or use the delay helper that tsyringe provides to defer a reference, though restructuring is the better fix.

**Interface parameters without @inject.** A parameter typed as an interface is emitted as Object in the metadata, so the container cannot know what to give it. Always use @inject(token) for interfaces.

Singletons capturing scoped values. A singleton resolved once keeps whatever it received at that time. Do not inject a per-request value into a singleton, because the first request's value will stay forever.

Leaking global state between tests. Registrations on the global container persist across test files in one process. Use child containers or reset in teardown.

Should you use a container at all

tsyringe is useful when the graph is large enough that manual wiring is tedious and when you want request scopes without writing them yourself. Its costs are decorators and metadata emission, which tie you to compiler settings and to a toolchain that supports them, and resolution at run time, so a missing registration fails when resolved and not when compiled. For small programs, a composition root with plain constructor arguments has no such costs and the same testability. Because tsyringe classes use ordinary constructor injection, you can start by hand-wiring and add the container later without rewriting the classes.

Also inTypeScript
Share

Keep reading

Flat illustration of an editor window full of code, with the TypeScript, npm and Node.js logos.
TypeScript

Type Inference in TypeScript

TypeScript works out most types for you. Learn how inference treats let and const, arrays, return values and callbacks, and when to write a type yourself.

7 min read
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.