DI BagOrdinary services. Checked composition. Explicit ownership.
A missing dependency is a type error. One feature is one directory that type-checks alone. Resources have one owner.
A missing dependency is a type error. One feature is one directory that type-checks alone. Resources have one owner.
Dependency injection for TypeScript where the compiler checks the wiring. A module keeps a feature's services private behind named exports; a container creates services on first use and releases what it owns when closed.
Documentation · npm · Quickstart · Modules as units of work · Comparison · Tutorial · API reference
Using a coding agent? The rules, the API card, the recipes, and every error message ship in the package. Paste this into your agent:
If di-bag is installed: read node_modules/di-bag/AGENTS.md first and follow its rules.
Use node_modules/di-bag/docs/agent/api-card.md for a call's signature and example,
node_modules/di-bag/docs/agent/recipes.md for a task, and
node_modules/di-bag/docs/agent/errors.md for a compiler or runtime message.
If di-bag is not installed: evaluate it from these pages before deciding.
- https://dany-fedorov.github.io/di-bag/ : what it does, the compiler check, a module in one screen
- https://dany-fedorov.github.io/di-bag/llms-full.txt : AGENTS.md, the API card, recipes, and errors in one file
- https://dany-fedorov.github.io/di-bag/guides/examples-modularity.html : the module layout and three runnable programs
- https://dany-fedorov.github.io/di-bag/guides/comparison.html : how it differs from Awilix, InversifyJS, TSyringe, Typed Inject, Effect, and NestJS
To install: npm install di-bag. It needs TypeScript 6.0.3 or later with "strict": true and has no
runtime dependencies. Node, Bun, and Deno need nothing else; in browsers and workers, pass
factoryReturnKind to each factory. After installing, read node_modules/di-bag/AGENTS.md.tsc names the missing service. Change a contract and tsc rejects the consumer that no longer fits. See it.tsconfig.json verify the module without the rest of the application. See a module.close() runs it, dependents first. A child container per request releases what the request acquired. See ownership.No decorators, no reflection metadata, no base classes, and zero runtime dependencies. Runs on Node, Bun, Deno, browsers, and workers.
npm install di-bagTypeScript 6.0.3 or later with strict enabled. Browsers and workers need one extra option per factory; see runtime support. Coming from 0.4? See upgrading.
A factory creates a service. The type of a factory's one object parameter declares what it depends on. A container calls factories on first use:
import { DiBag } from 'di-bag';
const app = DiBag.createBuilder()
.withServices({
config: () => ({ greeting: 'Hello' }),
greeter: ({ config }: { config: { greeting: string } }) => ({
greet(name: string) {
return `${config.greeting}, ${name}!`;
},
}),
})
.buildContainer();
const greeter = app.resolve('greeter');
console.log(greeter.greet('Ada')); // Hello, Ada!
await app.close();resolve('greeter') creates the greeter and its config the first time, and returns the same greeter afterwards. TypeScript knows that greeter has a greet(name: string): string method, with no cast and no token.
Remove the config factory. buildContainer() no longer type-checks, and the message names the missing service:
import { DiBag } from 'di-bag';
const incomplete = DiBag.createBuilder().withServices({
greeter: ({ config }: { config: { greeting: string } }) => ({
greet(name: string) {
return `${config.greeting}, ${name}!`;
},
}),
});
// @ts-expect-error required services are missing: config
incomplete.buildContainer();required services are missing: config; see https://dany-fedorov.github.io/di-bag/agent/errors.html#missing-serviceChange greeting to a number and, with default settings, the message is provided service does not satisfy its consumer dependency. With "noErrorTruncation": true in tsconfig.json, the details name the consumer, the dependency, the expected type, and the provided type. The error index lists every message with its cause and fix. The directive above is not decoration: this repository compiles the block in CI, and an unused @ts-expect-error fails the build.
A DI Bag module seals a service graph with the keys it exports. The host supplies the module's requirements, and a DI Bag container owns the services created at runtime. The file suffixes mark each role. See the full layout and the per-module check in AGENTS.md.
// src/features/greeting/contract.ts
export type Greeter = { greet(name: string): string };
export type GreetingConfig = { greeting: string };// src/features/greeting/greeting.di-bag-module.ts
import { DiBag } from 'di-bag';
import type { Greeter, GreetingConfig } from './contract.js';
export const greetingDiBagModule = DiBag.createBuilder()
.withServices({
template: ({ config }: { config: GreetingConfig }) => config.greeting,
greeter: ({ template }: { template: string }): Greeter => ({
greet: name => `${template}, ${name}!`,
}),
})
.buildModule({ exportedServiceKeys: ['greeter'], moduleLabel: 'greeting' });// src/app.di-bag-container.ts
import { DiBag } from 'di-bag';
import type { GreetingConfig } from './features/greeting/contract.js';
import { greetingDiBagModule } from './features/greeting/greeting.di-bag-module.js';
export function createAppDiBagContainer() {
return DiBag.createBuilder()
.withInstalledModules([greetingDiBagModule])
.withServices({ config: (): GreetingConfig => ({ greeting: 'Hello' }) })
.buildContainer();
}// src/main.ts
import { createAppDiBagContainer } from './app.di-bag-container.js';
const appDiBagContainer = createAppDiBagContainer();
try {
console.log(appDiBagContainer.resolve('greeter').greet('Ada')); // Hello, Ada!
} finally {
await appDiBagContainer.close();
}appDiBagContainer.resolve('template') is a type error because template is private. Leave out the config factory and the host fails with required services are missing: config. Another module may also call a private service template; the names never meet. Modules as units of work explains the layout, the check file, and the merge check.
Use createIndependentContainer() for a test with a replacement dependency. This example uses the graph from the quickstart:
import { DiBag } from 'di-bag';
const app = DiBag.createBuilder().withServices({
config: () => ({ greeting: 'Hello' }),
greeter: ({ config }: { config: { greeting: string } }) =>
({ greet: (name: string) => `${config.greeting}, ${name}!` }),
}).buildContainer();
const testApp = app.createIndependentContainer(['config'], {
config: () => ({ greeting: 'Hi' }),
});
try {
console.log(testApp.resolve('greeter').greet('Ada')); // Hi, Ada!
console.log(app.resolve('greeter').greet('Ada')); // Hello, Ada!
} finally {
await testApp.close();
await app.close();
}The replacement must satisfy the original service contract. Each independent container owns its own acquisitions and disposal. Close it separately. Factories can still return shared objects captured outside the container.
An async factory provides a promise. Declare that promise in any dependent factory and await it where you need the value:
import { DiBag } from 'di-bag';
const app = DiBag.createBuilder()
.withServices({
greeting: async () => 'Hello',
message: async ({ greeting }: { greeting: Promise<string> }) =>
`${await greeting}, Ada!`,
})
.buildContainer();
console.log(await app.resolve('message')); // Hello, Ada!
await app.close();Within one container, repeated resolutions share the same pending promise. Synchronous factories keep returning ordinary values. See async behavior for details.
Use DiBag.providerWithDisposal to tell the container how to release a factory's result:
import { DiBag } from 'di-bag';
const resources = DiBag.createBuilder()
.withServices({
cache: DiBag.providerWithDisposal({
provider: () => new Map<string, string>(),
disposeService: cache => cache.clear(),
}),
})
.buildContainer();
try {
resources.resolve('cache').set('answer', '42');
} finally {
await resources.close();
}The same pattern works for connections, clients, and subscriptions. Disposal can be asynchronous. Dependents close before their dependencies, and resources that were never created need no disposal. Ordinary factories return borrowed values. Having a close() method alone does not transfer ownership to the container.
| Operation | What it creates | Who closes it? |
|---|---|---|
container.createChildContainer() | A tracked child with its own scoped services | Close it when its work ends. The parent closes live children. |
container.createChildContainer(keys, providers) | A tracked child with selected scoped or transient services replaced | Close it when its work ends. The parent closes live children. |
container.createIndependentContainer() | A separate container with fresh instances | The caller closes it separately. |
container.createIndependentContainer(keys, providers) | A separate container with selected dependencies replaced | The caller closes it separately. |
An unmarked provider is scoped. Choose singleton explicitly when child containers should share it.
For request handling, checked test replacements, and loading dynamic features, see the server guide and Integration patterns.
The tutorial also covers typed tokens, class and function adapters, optional and lazy dependencies, collections, service readiness, metadata, observers, and plugin validation.
A module is the unit of work one person or one coding agent can own: a directory with a small exported contract, private services, and its own tests. Composition is checked when the modules meet, so several can be developed in parallel and merged with confidence.
buildModule({ exportedServiceKeys }) exports only the named services. Private services and their types stay inside, and two modules can use the same private names.verifyGraphAtCompileTime(); tests use createIndependentContainer(keys, providers) for checked replacements.buildContainer() or verifyGraphAtCompileTime(); di-bag-graph exports the declared edges and cycles for review.If two modules require the same name for different contracts, rename each requirement at the install site with withRenamedRequirement({ currentRequirementKey, newRequirementKey }), and colliding exports with withRenamedExport({ currentExportKey, newExportKey }).
The directory layout is the map: one directory per module, the contract first. The modules guide shows the layout and three runnable programs. LLM harnesses and agent graphs are one application of the pattern; the agent harness guide is a complete example.
DI Bag's appeal is the combination of object-parameter factories, checks across the declared graph, and explicit resource ownership. Decorator-free composition, async factories, and TypeScript support are also available in other libraries.
| Alternative | Reasons to choose it | DI Bag's different emphasis |
|---|---|---|
| Manual dependency injection | Direct function calls may be all a small application needs. TypeScript checks their arguments. | Adds lazy caching, graph-wide composition checks, child containers, and coordinated disposal. |
| Awilix | Function and class registration, inferred cradle types, lifetime options, and runtime strict checks. | Checks declared factory requirements against the registrations at compile time. |
| InversifyJS / TSyringe | Token and class-oriented containers; Inversify also offers decorator-free factory bindings and awaited async resolution. | Starts with object-parameter factories and immutable builders; checks accumulated graph contracts. |
| Typed Inject | A close alternative with compile-time dependency checks, explicit dependency tuples, child injectors, and disposal. | Adds object-parameter dependencies, forward references, private module exports, and selected service readiness with rollback. |
| Effect Context / Layer | Typed requirements, scoped resources, and composition within Effect's broader async and error model. | Keeps ordinary T and Promise<T> service values and explicit container ownership. |
| NestJS / Angular DI | Their native containers connect directly to framework components, testing tools, and lifecycles. | Provides standalone composition; applications supply the framework integration. |
See the comparison guide for primary sources, differences in async and disposal behavior, and the limits of these comparisons. There is no verified performance ranking against these libraries.
The package has zero runtime dependencies and one entry point: di-bag. The root import configures native Promise detection on Node, Bun, and Deno. It also bundles for browsers and workers because it has no node: imports.
In browsers and workers, buildContainer() names any factory that needs an explicit return kind. Register synchronous factories with DiBag.createProvider(factory, { factoryReturnKind: 'sync-value' }) and native Promise factories with 'native-promise'. See portable mode.
Promise<T> exposes that promise. Consumers declare and await it themselves.close() pending. Pass close({ waitTimeoutMs, abortSignal }) to stop waiting. The rejection names the disposers still running, and disposal continues in the background.di-bag-graph.di-bag and node:*.| Resource | What you'll find |
|---|---|
| Complete tutorial | Learn every public API through examples, from first composition to advanced ownership. |
| API reference | Exact generated signatures, overloads, type parameters, and API inventories. |
| Server guide | Node HTTP, Express, Fastify, Bun, and Deno: shared services, request containers, service readiness, and shutdown. |
| React guide | Browser applications: one app runtime at bootstrap, project runtimes owned from effects, Strict Mode, cancellation, bounded teardown, and useSyncExternalStore. |
| Modules as units of work | The recommended module layout, separately owned features, isolated tests, and contributed tools. |
| Agent docs | Rules, module layout, and check commands for coding agents, with recipes and errors. Shipped in the package. |
| Agent harnesses and graphs | One worked application: model and tool modules, metadata inspection, and node tests with typed fixtures. |
| Static dependency graph | Export every builder chain, declared edge, and cycle to JSON with di-bag-graph for merge review and CI. |
| Runnable examples | One program per topic: modules, tokens, composition, collections, plugins, observers, child containers, and provider metadata. |
| Integration patterns | Tested recipes for request ownership, substitutions, and dynamic features. |
| Comparison with alternatives | When DI Bag or another approach may be a better fit, with primary sources. |
| Development and verification | Full checks, portable runtime testing, compiler scale, and performance evidence. |
| Documentation map | Every guide, the generated reference, and the contributor documents. |
After npm ci, run the main checks with Node and Bun installed:
npm run platform:pin
npm run check
npm run check:nativeRun an example with bun run examples/composition.ts. The development guide covers the remaining compiler, platform, and packaging checks and their tool requirements.
The API is pre-1.0 and includes breaking changes. Run the 0.4-to-0.5 codemod before upgrading, while the 0.4 types are still installed, then read the 0.5 migration guide and the changelog:
npx di-bag-codemod --project tsconfig.json --writeMIT © Dany Fedorov