How to Use InversifyJS for Dependency Injection
Learn how to use InversifyJS 6 for dependency injection in TypeScript: bindings, identifiers, scopes, tests with rebind, and the decorator settings you need.

InversifyJS is a dependency injection container for TypeScript. You describe how each service is built through bindings, mark classes with decorators, and ask the container for the object you need: it constructs the whole graph, in the right order, with the right lifetimes. This guide uses the InversifyJS 6 API with TypeScript 5.9 on Node.js 24, and walks through installation, identifiers, constructor injection, scopes, factories, replacing bindings in tests and the pitfalls that catch newcomers. Check the release notes of any newer major version before upgrading, since a major release can change method signatures.
When a container helps
If you wire dependencies by hand in a composition root, a container automates the same job. It becomes worth its weight when the graph has dozens of services, when you need lifetimes such as one instance per application or one per request, or when different environments bind different implementations. For a small application, manual wiring is simpler, and the previous post on dependency injection without a framework covers it. Inversify is the tool to reach for when the manual root has become the part nobody enjoys editing.
Installation and TypeScript settings
Install the package and the metadata polyfill it relies on.
npm install inversify reflect-metadataInversify 6 reads constructor parameter metadata through decorators, so the compiler options must emit it.
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"strict": true
}
}experimentalDecorators enables the older decorator syntax that the library uses, and emitDecoratorMetadata makes TypeScript record the types of constructor parameters. The metadata polyfill must be imported once, before anything else runs, at the very top of your entry file: import "reflect-metadata";. Because these decorators are not erasable syntax, Node.js cannot run the files by stripping types alone. Compile with tsc, or run through a tool such as tsx that transforms the decorators.
Step 1: identifiers for the things you inject
A container looks things up by an identifier. For classes you can use the class itself, but for interfaces, which do not exist at run time, you need a token. A Symbol avoids collisions.
export interface Logger {
info(message: string): void;
}
export const TYPES = {
Logger: Symbol.for("Logger"),
UserRepository: Symbol.for("UserRepository"),
UserService: Symbol.for("UserService"),
};Keeping the identifiers in one file gives you a single list of what the application can inject. Symbol.for returns the same symbol for the same key across modules, which helps when two packages need to agree on an identifier.
Step 2: mark classes injectable
Every class the container constructs needs the @injectable() decorator. A parameter that is not a class, such as an interface, needs @inject(identifier).
import "reflect-metadata";
import { inject, injectable } from "inversify";
import { TYPES, type Logger } from "./types.ts";
@injectable()
export class ConsoleLogger implements Logger {
info(message: string): void {
console.log(message);
}
}
@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 UserService {
constructor(
@inject(TYPES.Logger) private readonly logger: Logger,
@inject(TYPES.UserRepository) private readonly repository: UserRepository,
) {}
greet(id: number): string {
const name = this.repository.findName(id) ?? "stranger";
this.logger.info(`greeting ${name}`);
return `Hello, ${name}`;
}
}The service depends on a Logger interface and a repository, and it does not know how either is created. Its own code has no new.
Step 3: bind identifiers to implementations
The container is where you decide which implementation answers each identifier.
import { Container } from "inversify";
import { ConsoleLogger, UserRepository, UserService } from "./services.ts";
import { TYPES, type Logger } from "./types.ts";
export const container = new Container();
container.bind<Logger>(TYPES.Logger).to(ConsoleLogger).inSingletonScope();
container.bind<UserRepository>(TYPES.UserRepository).to(UserRepository).inSingletonScope();
container.bind<UserService>(TYPES.UserService).to(UserService);import "reflect-metadata";
import { container } from "./container.ts";
import { TYPES } from "./types.ts";
import type { UserService } from "./services.ts";
const service = container.get<UserService>(TYPES.UserService);
console.log(service.greet(1));
console.log(service.greet(9));greeting Ada
Hello, Ada
greeting stranger
Hello, strangercontainer.get looked up UserService, saw that it needs a logger and a repository, resolved those first and passed them to the constructor. You never wrote new UserService(...). All the knowledge of which classes implement which interface lives in container.ts, so changing the logger is a one-line edit there.
Scopes: how long an instance lives
A binding's scope decides when the container creates a new instance.
| Scope | Behavior |
|---|---|
| Transient (default) | A new instance each time it is resolved |
| Singleton | One instance for the life of the container |
| Request | One instance per container.get call and its dependency graph |
import "reflect-metadata";
import { Container, injectable } from "inversify";
@injectable()
class Counter {
static created = 0;
readonly id = ++Counter.created;
}
const container = new Container();
container.bind("transient").to(Counter);
container.bind("singleton").to(Counter).inSingletonScope();
const a = container.get<Counter>("transient");
const b = container.get<Counter>("transient");
const c = container.get<Counter>("singleton");
const d = container.get<Counter>("singleton");
console.log(a.id, b.id, c.id, d.id);
console.log(a === b, c === d);1 2 3 3
false trueThe two transient resolutions produced different objects with ids 1 and 2. The singleton was created on the first request, as id 3, and reused for the second. Choose singletons for stateless services and shared resources, such as a database client or a logger, and transient for objects that hold per-use state. You can also set a default for the whole container with the defaultScope option in the constructor. Be careful about injecting a transient or request-scoped object into a singleton: the singleton captures it once, and it then lives as long as the singleton does, which defeats the narrower scope.
Other binding types
to(Class) is the common case, and others cover the rest.
import "reflect-metadata";
import { Container } from "inversify";
const container = new Container();
container.bind<string>("apiUrl").toConstantValue("https://api.example.com");
container
.bind<{ now: () => string }>("clock")
.toDynamicValue(() => ({ now: () => "2026-11-20T10:00:00Z" }));
container.bind<(n: number) => number>("double").toFunction((n) => n * 2);
console.log(container.get<string>("apiUrl"));
console.log(container.get<{ now: () => string }>("clock").now());
console.log(container.get<(n: number) => number>("double")(21));https://api.example.com
2026-11-20T10:00:00Z
42toConstantValue binds a value you already have, such as configuration. toDynamicValue runs a function when the dependency is resolved, which suits objects that need setup from other bindings or from the environment. toFunction binds a plain function. There is also toFactory for cases where the consumer decides at call time which instance it needs and with what arguments.
Replacing bindings in tests
A test needs the same graph with a fake in one place. Take a snapshot of the container, rebind the identifier and restore afterwards.
import "reflect-metadata";
import assert from "node:assert/strict";
import { afterEach, beforeEach, test } from "node:test";
import { container } from "./container.ts";
import { TYPES, type Logger } from "./types.ts";
import type { UserService } from "./services.ts";
const lines: string[] = [];
beforeEach(() => {
container.snapshot();
container.rebind<Logger>(TYPES.Logger).toConstantValue({ info: (m) => void lines.push(m) });
});
afterEach(() => {
container.restore();
lines.length = 0;
});
test("greet logs the name it found", () => {
const service = container.get<UserService>(TYPES.UserService);
assert.equal(service.greet(2), "Hello, Lin");
assert.deepEqual(lines, ["greeting Lin"]);
});✔ greet logs the name it found (1.4ms)
ℹ tests 1
ℹ pass 1
ℹ fail 0snapshot saves the bindings and restore brings them back, so one test's override does not leak into the next. An alternative that avoids global state is to build a fresh container per test, from a function such as createContainer() that the production entry point also uses. A function that returns a container keeps the wiring in one place and makes tests independent.
Pitfalls
**Missing @injectable().** Inversify throws an error at resolution time if a class it must construct lacks the decorator. The message names the class, so the fix is quick, but the failure appears at run time, not at compile time.
Missing binding. Asking for an identifier with no binding fails with an error that names the identifier. Because the graph is built lazily on get, a missing binding deep in the graph surfaces only when something resolves it. Write one test that resolves every top-level service, so a missing binding fails in continuous integration.
Circular dependencies. If A needs B and B needs A, construction cannot succeed. Inversify reports the cycle. Break it by extracting shared logic into a third class, which is almost always the better design than a lazy reference.
Decorators and bundlers. Tools that compile TypeScript file by file without type information, which can be the case with some fast transpilers, may fail to emit design:paramtypes metadata. Use @inject explicitly on every parameter, which is what the examples above do, so you do not depend on emitted types.
Service locator creep. Do not pass the container into classes so they can call container.get themselves. That hides dependencies. Ask the container only at the top, in the entry point, and let it inject everything below.
Structuring a larger application
Group related bindings in container modules, which Inversify provides, so each feature registers itself.
import { ContainerModule } from "inversify";
import { ConsoleLogger, UserRepository, UserService } from "./services.ts";
import { TYPES, type Logger } from "./types.ts";
export const userModule = new ContainerModule((bind) => {
bind<Logger>(TYPES.Logger).to(ConsoleLogger).inSingletonScope();
bind<UserRepository>(TYPES.UserRepository).to(UserRepository).inSingletonScope();
bind<UserService>(TYPES.UserService).to(UserService);
});The entry point calls container.load(userModule), and other features add their own modules. The composition stays readable as the application grows, and a test can load only the modules it needs.


