Dependency Injection
Docs Home | Previous: Response Validation | Next: Modules
bun-openapi includes a lightweight DI container with provider tokens and scopes.
Provider Forms
Register providers in createApp({ providers }) or inside a @Module. Five forms are supported:
| Form | Usage |
|---|---|
| Class shorthand | UserService — registers the class as its own token |
useClass | { provide: Token, useClass: UserService } |
useValue | { provide: Token, useValue: value } — wraps an existing instance |
useFactory | { provide: Token, useFactory: (a, b) => val, inject: [A, B] } |
useExisting | { provide: NewToken, useExisting: ExistingToken } — alias |
Provider Tokens
A token can be a class constructor, a string, or a symbol.
Registering Services
Mark every class you want the container to manage with @Injectable():
Register both the service and its dependencies in providers:
Constructor Injection
For class tokens (the common case), the container resolves the dependency automatically using reflect-metadata — no decorator needed on the parameter:
For string or symbol tokens, use @Inject(token) on the constructor parameter:
Field Injection
@Inject(token) also works on class fields:
Injecting External Instances (ValueProvider)
Use useValue to hand an existing object — for example a TypeORM DataSource — into the container so services can receive it instead of importing the singleton directly:
Because DataSource is a class token, reflect-metadata resolves it without @Inject. See examples 11–14 for working implementations of this pattern.
Factory Provider
Use useFactory when the value depends on other providers:
Scopes
| Scope | Behaviour |
|---|---|
"singleton" (default) | One instance for the lifetime of the app, shared across all requests |
"request" | A fresh instance per request, isolated to that request's scope |
Examples
- 04_dependency-injection — service tokens,
@Inject, value providers - 11_jwt-auth —
DataSourceValueProvider, JWT guard as injectable - 12_form-auth —
DataSourceValueProvider, injectable guard - 13_typeorm-relations —
DataSourceValueProvider, multiple repositories from one injected source - 14_session-auth —
DataSourceValueProvider alongside an in-memorySessionStore