Providers
Providers are the backbone of MiiaJS's dependency injection (DI) system. A class decorated with @Injectable() and declared in a module can be injected into the other classes of that module, and into modules that import it once the module exports it - see Modules → Boundaries.
Defining a provider
import { Injectable } from '@miiajs/core'
@Injectable()
class UserService {
findAll() {
return [{ id: 1, name: 'Alice' }]
}
findById(id: string) {
return { id, name: 'Alice' }
}
}
Register the provider in a Module:
@Module({
controllers: [UserController],
providers: [UserService],
})
class UserModule {}
app.provide() registers a provider on the app itself, outside any module - for a script or a test without modules. It does not replace what a module declares: providing a token that a loaded module declares throws, and the replacement in a test is override():
[Miia] provide(UserService): UserService is declared by UserModule - replace it with override() instead
A class passed to provide() takes its scope from its @Injectable(), as it would in a module; a factory provider takes the scope given to provider(). A provided token has no module, so every module can see it. What the provider itself injects is checked from the root: it sees what the modules passed to app.register() export.
Injecting dependencies
Call inject() in a field initializer to resolve a dependency:
import { Controller, Get, inject } from '@miiajs/core'
@Controller('/users')
class UserController {
private userService = inject(UserService)
@Get('/')
list() {
return this.userService.findAll()
}
}
Typed tokens
A class is the simplest token: inject(UserService) returns a UserService. For a value that is not an instance of a class you register - an interface, an options object, a third-party client - create a token with createToken<T>() and register it with provider():
import { createToken, inject, Injectable, Module, provider } from '@miiajs/core'
interface Mailer {
send(to: string, body: string): Promise<void>
}
export const MAILER = createToken<Mailer>('Mailer')
@Module({
providers: [provider(MAILER, () => new SmtpMailer())],
exports: [MAILER],
})
class MailModule {}
@Injectable()
class NotificationService {
private mailer = inject(MAILER) // Mailer
}
@Module({ imports: [MailModule], providers: [NotificationService] })
class NotificationsModule {}
A token is identified by the object itself, not by its name: two createToken('Mailer') calls make two different tokens. Export the token from the file that provides it and import it where it is used.
token.name is the name the token was given. For a token you create it only shows up in messages, but the tokens from defineModel() and defineConfig() use it at runtime too: it is the mongoose model name, the papr collection and the config name, so defineModel('User', schema).name is 'User'. The kind option of createToken() says what the token is. Messages show a token with a kind as kind(name) and one without as its name, and formatToken(token) returns that label:
import { createToken, formatToken } from '@miiajs/core'
const MAILER = createToken<Mailer>('Mailer')
const BILLING_MAILER = createToken<Mailer>('billing', { kind: 'Mailer' })
formatToken(MAILER) // 'Mailer'
formatToken(BILLING_MAILER) // 'Mailer(billing)'
The packages label their tokens this way: MongooseModel(User), Config(payments), drizzleDb(analytics), and drizzleDb() for the default connection, whose name is ''.
provider(token, factory, { scope?, deps?, shared? }) builds a factory provider and checks what the factory returns against the token, so provider(MAILER, () => 42) is a type error. The factory can take a resolve function to reach other providers:
provider(MAILER, (resolve) => new SmtpMailer(resolve(ConfigService).getOrThrow('SMTP_URL')))
The type flows from the token wherever it is resolved: inject(), injectOptional(), app.get(), ctx.resolve(), Resolver and TestApp.resolve().
Abstract classes as tokens
An abstract class works as a token too. It keeps the contract apart from the implementation without a separate token object:
abstract class Storage {
abstract read(key: string): Promise<string | null>
}
class MemoryStorage extends Storage {
private data = new Map<string, string>()
async read(key: string) {
return this.data.get(key) ?? null
}
}
@Module({ providers: [provider(Storage, () => new MemoryStorage())], exports: [Storage] })
class StorageModule {}
@Injectable()
class FileService {
private storage = inject(Storage) // Storage, built by MemoryStorage
}
Hints in "No provider" errors
A hint says where a token comes from. Pass it to createToken() or to @Injectable():
export const MAILER = createToken<Mailer>('Mailer', { hint: 'MailModule.configure()' })
@Injectable({ hint: 'UsersModule' })
export class UsersService {}
When the token is not registered, the error names its source:
[Miia] No provider found for token: Mailer, required by NotificationService (NotificationsModule)
- Mailer is provided by MailModule.configure(); import that module where Mailer is used
When another token with the same label (kind(name)) and the same hint is registered, the error adds a line. Either the token is defined twice on purpose - two defineModel('User', ...) calls, one per connection - and this one is not registered yet, or two copies of the package that defines it are installed, each creating its own token object:
- another token named Mailer with the same hint is registered: register this one too if both are intended, otherwise deduplicate the package that defines it
Scopes
Providers support three scopes:
| Scope | Behavior | Use case |
|---|---|---|
singleton (default) | One instance for the app lifetime | Services, config, repositories |
transient | New instance on every injection | Stateless utilities, factories |
request | One instance per HTTP request, kept on the request context | Request-scoped state, loggers |
@Injectable({ scope: 'singleton' })
class DatabaseService {}
@Injectable({ scope: 'transient' })
class RequestParser {}
@Injectable({ scope: 'request' })
class RequestLogger {}
Controllers and guards are constructed once and must be singletons. The request scope is for providers you reach through ctx.resolve() or through inject() in another request-scoped provider.
Request scope
A request-scoped instance lives on the request context. The first ctx.resolve() in a request creates it, later calls in the same request return the same instance, and concurrent requests never share one. Call ctx.resolve() in a handler, middleware or guard:
import { Controller, Get, Injectable, type RequestContext } from '@miiajs/core'
@Injectable({ scope: 'request' })
class RequestLogger {
readonly requestId = crypto.randomUUID()
}
@Controller('/orders')
class OrderController {
@Get('/')
list(ctx: RequestContext) {
const logger = ctx.resolve(RequestLogger)
return { requestId: logger.requestId }
}
}
A request-scoped provider can inject() another request-scoped provider - both come from the same request:
@Injectable({ scope: 'request' })
class AuditTrail {
private logger = inject(RequestLogger) // the instance ctx.resolve(RequestLogger) returns in this request
}
The context of the request is a token too, REQUEST_CONTEXT: inject() it in a request-scoped class, resolve() it in a request-scoped factory:
import { createToken, inject, Injectable, provider, REQUEST_CONTEXT } from '@miiajs/core'
@Injectable({ scope: 'request' })
class RequestLogger {
private ctx = inject(REQUEST_CONTEXT)
readonly requestId = this.ctx.req.headers.get('x-request-id') ?? crypto.randomUUID()
}
export const TENANT = createToken<string>('Tenant')
provider(TENANT, (resolve) => resolve(REQUEST_CONTEXT).req.headers.get('x-tenant') ?? 'default', { scope: 'request' })
REQUEST_CONTEXT is request-scoped itself, so the rule below applies to it as well. It cannot be replaced with provide(), override() or a module's providers - every request seeds its own; test a request-scoped provider through a route (TestApp.request()), or override that provider itself.
Singletons and transients cannot inject() a request-scoped provider - they would keep the instance of whichever request built them. A singleton that tries fails at startup:
[Miia] OrderService (singleton) injects request-scoped RequestLogger - resolve it with ctx.resolve() in the handler, or make OrderService request-scoped
A transient fails the same way when it is constructed, even when a request-scoped provider is the one injecting it.
Outside a request there is no instance to return, so app.get() throws for a request-scoped token:
[Miia] Request-scoped RequestLogger can only be resolved inside a request (ctx.resolve)
Resolver throws for one even inside a request - it has no request to keep the instance on:
[Miia] Request-scoped RequestLogger cannot be resolved through Resolver - use ctx.resolve(), or inject() it in a request-scoped provider
The end of a request
Once the pipeline of a request has finished and its response is built, every instance the request created gets onDestroy(), newest first - a provider before the request-scoped providers it injected. The hooks run after the response is built and do not hold it back. They run one at a time - a hook that returns a promise is awaited before the next one starts - and a hook that throws or rejects is logged while the rest still run. Request-scoped instances get no other lifecycle hook.
@Injectable({ scope: 'request' })
class RequestMetrics {
private metrics = inject(MetricsService)
private started = performance.now()
onDestroy() {
this.metrics.record('request.duration', performance.now() - this.started)
}
}
Only what the request created is destroyed. A request-scoped factory that returns a singleton - provider(CurrentRepo, (resolve) => resolve(UserRepo), { scope: 'request' }), picking a repository per tenant - does not hand that singleton to the request: UserRepo gets its onDestroy() from app.destroy(), not after every request. The same goes for a lazy proxy a request-scoped factory returns (createLazyProxy()) and for the context itself.
After that, ctx.resolve() of a request-scoped token throws, so nothing creates an instance that no one would destroy. Singletons and transients still resolve:
[Miia] Request-scoped RequestLogger was resolved after its request finished (e.g. from a streaming response) - resolve it in the handler before returning
A streaming response is still being read after the pipeline has finished. Resolve what the stream needs in the handler, and do not count on a request-scoped instance staying usable while it streams - its onDestroy() may already have run. app.destroy() waits for the onDestroy() of requests that finished before shutdown started, before any onShutdown(), so their hooks still see working singletons. The onDestroy() of a request still running when shutdown starts is not waited for, and neither is that of one that finishes after it started - with no server to close (app.fetch in serverless), requests that keep coming in do not delay shutdown. There is no timeout: a hook that never settles holds destroy() up.
Optional injection
Use injectOptional() when a provider might not be registered:
import { injectOptional } from '@miiajs/core'
@Injectable()
class NotificationService {
private email = injectOptional(EmailService) // null if not registered
}
null means nothing registers the token. A token that is registered but not visible from the module - its module does not export it, or is not imported - is a boundary violation, not null.
Runtime DI introspection (Resolver)
Resolver is a public read-only wrapper over the DI container. Inject it when the token is not known until runtime - plugin systems, conditional resolution, dynamic factories.
import { createToken, Injectable, inject, Module, provider, Resolver, type Token } from '@miiajs/core'
const PLUGINS: Record<string, Token<Plugin>> = {
csv: createToken<Plugin>('CsvPlugin'),
pdf: createToken<Plugin>('PdfPlugin'),
}
@Injectable()
class PluginRegistry {
private resolver = inject(Resolver)
load(name: string): Plugin {
const token = PLUGINS[name]
if (!token || !this.resolver.has(token)) {
throw new Error(`unknown plugin: ${name}`)
}
return this.resolver.resolve(token)
}
}
@Module({
providers: [
PluginRegistry,
provider(PLUGINS.csv, () => new CsvPlugin()),
provider(PLUGINS.pdf, () => new PdfPlugin()),
],
exports: [PluginRegistry],
})
class PluginsModule {}
The Resolver exposes only read operations. Mutations (register, destroyAll) stay internal to keep the public DI surface minimal:
| Method | Description |
|---|---|
has(token) | Returns true when a provider is registered for the token and the module of the resolver can see it. |
resolve<T>(token) | Resolves the provider; throws if the token is not registered. A request-scoped token throws too - resolve it with ctx.resolve(). |
resolveOptional<T>(token) | Resolves or returns null for an unregistered token. |
The resolver of a module
inject(Resolver) returns a resolver bound to the module of the provider that injects it - the same boundaries apply to it as to inject(). The registry above sees its own plugins, what PluginsModule imports and global exports, and nothing else:
has()isfalsefor a token the module cannot see, the same as for one nothing registers.resolve()andresolveOptional()of a registered token the module cannot see are a boundary violation.resolveOptional()returnsnullonly for a token nothing registers.- During startup - a
resolve()in a field initializer, say - the violation joins the startup report; later it throws on the call.
[Miia] 1 module boundary violation:
Resolver of PluginsModule resolved ReportsService (ReportsModule), which PluginsModule cannot see:
- add ReportsService to ReportsModule `exports`
- add ReportsModule to PluginsModule `imports`
Docs: /docs/core-concepts/modules#boundaries
A resolver keeps its module wherever it goes: passed to another object, it still sees what its own module sees. The resolve of a factory provider reaches a resolver bound to the factory's module (resolve(Resolver)), which, for a configure() result, also sees what the module importing it sees. A provider several modules declare - a shared provider, or one of a module class configured under several names - gets a resolver over all of them: has() is true only for a token every one of them sees, and resolve() is checked from each. app.get(Resolver), TestApp.resolve(Resolver), a provider registered with app.provide() and a guard no module declares get the resolver of the root, which sees what the modules passed to app.register() export.
Lifecycle hooks
Singleton providers can implement four lifecycle hooks:
@Injectable()
class DatabaseService {
async onInit() {
// Called during app.init() or lazily on first app.fetch(),
// after every singleton has been instantiated.
await this.connect()
}
async onReady() {
// Called after every onInit() has completed. Guaranteed to see
// a fully-initialized container regardless of registration order.
}
async onShutdown() {
// Called during app.destroy(), before any onDestroy(). Stop taking
// new work and wait for work in flight - stay usable for others.
await this.drainQueries()
}
async onDestroy() {
// Called during app.destroy(), after every onShutdown().
await this.disconnect()
}
}
| Hook | When called | Use case |
|---|---|---|
onInit() | During app.init() or lazily on first app.fetch(), after every singleton has been instantiated | Open connections, warm caches, load seed data |
onReady() | During app.init(), after every onInit() has completed | Ambient discovery, cross-wiring between providers |
onShutdown() | During app.destroy(), before any onDestroy() | Stop taking new work and wait for work in flight; stay usable, release resources in onDestroy() |
onDestroy() | During app.destroy(), after every onShutdown() | Close connections, flush buffers, release resources |
All four run on singleton providers. Transient providers get none, and a request-scoped instance gets only onDestroy(), at the end of its request - see Request scope.
onInit() and onReady() run in dependency order: a provider's hooks run after the hooks of everything it injects - through inject(), a factory's resolve() or Resolver.resolve() while it is being constructed - and of everything it lists in deps. Otherwise they run in registration order, but do not rely on the order between unrelated providers: a provider pulled forward by a dependent can run ahead of one registered before it. An instance registered under several tokens gets each hook once.
The ordering gives onReady a guarantee onInit lacks: by the time any onReady() runs, every singleton in the container already has a fully-initialized instance, regardless of registration order. This is what makes the Discovery Service safe to use - it can scan every provider for decorator metadata at startup without worrying about which provider was registered first.
onShutdown() and onDestroy() run in the reverse order: a provider's shutdown hooks run before those of everything it injects. Shutdown goes in two phases - onShutdown() on every singleton, then onDestroy() on every singleton - so nothing is released while another provider may still be finishing its work, whether or not the two are related. That is the contract for onShutdown(): stop taking new work and wait for the work in flight, but stay usable - another provider may still drain its own work through yours; release resources only in onDestroy().
A failing shutdown hook does not stop the rest. app.destroy() runs every hook, logs each failure with its source (DatabaseService.onDestroy() failed during shutdown), and throws once all of them have run - the error itself for a single failure, an AggregateError for several.
Factory providers
Register a provider with a custom factory function. The factory's resolve argument reaches other providers:
import { createToken, Module, provider } from '@miiajs/core'
export const DATABASE_URL = createToken<string>('DatabaseUrl')
export const DATABASE = createToken<Database>('Database')
@Module({
providers: [
provider(DATABASE_URL, () => process.env.DATABASE_URL ?? 'postgres://localhost/app'),
provider(DATABASE, (resolve) => createDatabase(resolve(DATABASE_URL))),
],
})
class AppModule {}
A factory provider that several modules declare - the way a register() call in each feature module does - can be marked { shared: key } so that they share one instance; see Shared providers.
Lazy dependencies: deps
A factory that calls resolve() while it runs needs nothing more - the container sees the call and orders the hooks by it. A factory that reaches a provider later, after construction, is invisible to the container. The common case is a factory that returns a proxy resolved on first use; list what it reaches in deps:
import { createLazyProxy, createToken, provider } from '@miiajs/core'
export const DB = createToken<Database>('Db')
provider(DB, (resolve) => createLazyProxy(() => resolve(DbService).db), { deps: [DbService] })
deps only orders lifecycle hooks: a provider that injects DB now gets its onInit() after DbService.onInit() has connected. A token in deps that nothing provides fails app.init() with No provider found for token: X, required by deps of Y (YModule), and so does a cycle that exists only through deps (a provider lists one that injects it). Like inject(), a token in deps must be visible from the module of the provider that lists it.
The resolve a factory receives stays bound to its provider: called later, from the lazy proxy, it is still checked from the provider's module, not from whatever happens to be under construction at the time.