Discovery Service
DiscoveryService lets a provider find, at startup, every class or method that carries a given decorator - across every other provider, controller, and guard in the app. You write @Cron('* * * * *'), @QueueHandler('emails'), or @On(UserCreated) on a method, and a discovery-aware service finds it automatically. No manual register([...]) list, no central registry to keep in sync.
This is the same mechanism the framework uses internally for @Get/@Post route discovery on controllers - DiscoveryService exposes it as a public API so userland packages and your own code can build the same pattern.
Mental model
The whole story is three steps:
- A custom decorator writes metadata to
Symbol.metadata[KEY]on the class at definition time. A method decorator pushes one entry per decorated method into an array under the symbol key; a class decorator stores one value under it. - The framework calls
onReady()on every singleton duringapp.init(), after everyonInit()has completed. By this point every provider in the container has a fully-initialized instance, regardless of registration order. - A singleton holding
inject(DiscoveryService)asks for that key in itsonReady().getMethodsWithMeta(KEY)returns a flat list of{ instance, ctor, methodName, metadata }- one per decorated method across the whole app - ready to bind handlers, register subscriptions, or whatever the discovery-aware service needs to do.getClassesWithMeta(KEY)returns{ instance, ctor, metadata }- one per instance whose class carries the key.
The key is the boundary: only instances whose class carries metadata under it come back. There is no call that lists every singleton - the symbol belongs to the package that defines the decorator, so the package sees exactly the classes that opted in. Module boundaries do not apply: discovery finds the classes of every module, exported or not.
This is exactly how @miiajs/messaging wires up @On handlers under the hood, and it's how any future scheduler, queue worker, or metrics package will work too.
DiscoveryService API
Inject DiscoveryService like any other provider, then call one of its two methods inside an onReady() hook - one for method decorators, one for class decorators.
import { DiscoveryService, Injectable, inject } from '@miiajs/core'
@Injectable()
class MyDiscoveryService {
private discovery = inject(DiscoveryService)
async onReady() {
const handlers = this.discovery.getMethodsWithMeta<HandlerMeta>(HANDLER)
const jobs = this.discovery.getClassesWithMeta<JobMeta>(JOB)
}
}
| Method | Returns | Description |
|---|---|---|
getMethodsWithMeta<M>(key) | DiscoveredMethod<M>[] | One entry per decorated method on every singleton whose class has metadata under key. The primary API for ambient discovery. |
getClassesWithMeta<M>(key) | DiscoveredClass<M>[] | One entry per singleton whose class has metadata under key - for class decorators. |
Transient and request-scoped providers are deliberately excluded - they have no stable instance to bind a handler to. If you need discovery on those, restructure as a singleton.
The shapes the two methods return:
interface DiscoveredMethod<T extends DiscoverableMethodMeta> {
instance: object
ctor: Constructor
methodName: string
metadata: T
}
interface DiscoveredClass<M = unknown> {
instance: object
ctor: Constructor
metadata: M
}
Bind a handler with (instance as any)[methodName].bind(instance) and you have a callable function that preserves this.
What comes back, and when:
- Metadata is read from the class of the instance.
ctoris the class of what the provider holds, not the token it is registered under: a factory providerprovider(token, () => new Handlers())is discovered asHandlers, and a factory that returns a subclass is discovered as the subclass. A plain object has no class of its own, so it is never discovered - see Testing for mocks. A lazy proxy fromcreateLazyProxy()is skipped too; its target is discovered when it is registered itself. - One entry per instance. An instance registered under two tokens comes back once. One class provided twice comes back twice - whether that is an error is up to the package;
@miiajs/messagingrejects it at startup. - Only once every provider is constructed. Called earlier - from a constructor or a field initializer, or after
app.get()withoutinit()- both methods throw[Miia] DiscoveryService.getMethodsWithMeta() was called before every provider was constructed. Call them fromonReady()(oronInit()).
The DiscoverableMethodMeta convention
getMethodsWithMeta() doesn't know the shape of your metadata - it relies on a single contract: the metadata stored under key must be an array of objects, and each object must include a handlerName: string field. The framework uses handlerName to bind the discovered metadata back to the actual method on the instance.
interface DiscoverableMethodMeta {
handlerName: string
}
Everything else in the metadata object is yours to define. A minimal custom decorator looks like this:
import { createMethodDecorator, pushMeta } from '@miiajs/core'
const METRIC = Symbol('metric')
interface MetricMeta {
handlerName: string
name: string
}
export const Metric = createMethodDecorator<[name: string]>(
(_target, ctx, name) => {
pushMeta(ctx.metadata!, METRIC, {
handlerName: ctx.name as string,
name,
} satisfies MetricMeta)
},
)
Use ctx.name from the TC39 decorator context to capture the method name automatically. The user just writes @Metric('signups') async onSignup() {} and the convention is satisfied.
The onReady lifecycle hook
onReady() is the third provider lifecycle hook, called after every onInit() has completed. It exists specifically to give discovery-aware services a safe scanning point - by the time any onReady() runs, every singleton in the container is fully initialized, so a single sweep through getMethodsWithMeta() will find every decorated method without race conditions.
Two caveats worth internalising:
- Don't
emitor trigger work from insideonInit()oronReady().onReady()hooks run in dependency order - a provider's hook after the hooks of the singletons it injects - but between unrelated providers the order is not guaranteed. IfOtherService.onReady()fires an event that reaches a handler on a provider it does not depend on, that provider's ownonReady()- where it would open a connection or warm a cache - might not have run yet. Lifecycle hooks should scan and subscribe, not trigger work. Real work happens later - in request handlers, timers, or external triggers. onReadyis singleton-only, same asonInitandonShutdown. Transient providers run no lifecycle hooks, and request-scoped ones onlyonDestroy(), at the end of their request.
Complete example: a tiny event emitter
Here's the entire DiscoveryService pattern in one example: a 30-line in-process event emitter built on pure @miiajs/core, with no ecosystem dependencies. This is exactly the pattern @miiajs/messaging implements - with retry, DLQ, and pluggable transports layered on top.
import {
createMethodDecorator,
DiscoveryService,
Injectable,
inject,
Module,
pushMeta,
type DiscoverableMethodMeta,
} from '@miiajs/core'
// 1. The decorator
const FIRE = Symbol('fire')
interface FireMeta extends DiscoverableMethodMeta {
topic: string
}
const Fire = createMethodDecorator<[topic: string]>((_target, ctx, topic) => {
pushMeta(ctx.metadata!, FIRE, {
handlerName: ctx.name as string,
topic,
} satisfies FireMeta)
})
// 2. The discovery-aware bus
type Handler = (payload: unknown) => void | Promise<void>
@Injectable()
class MiniEventBus {
private discovery = inject(DiscoveryService)
private handlers = new Map<string, Handler[]>()
async onReady() {
for (const { instance, methodName, metadata } of this.discovery.getMethodsWithMeta<FireMeta>(FIRE)) {
const list = this.handlers.get(metadata.topic) ?? []
list.push(((instance as any)[methodName] as Handler).bind(instance))
this.handlers.set(metadata.topic, list)
}
}
async emit(topic: string, payload: unknown) {
for (const fn of this.handlers.get(topic) ?? []) await fn(payload)
}
}
// 3. A provider with a discovered handler
@Injectable()
class NotificationService {
@Fire('user.created')
async sendWelcome(payload: unknown) {
console.log('welcome:', payload)
}
}
// 4. Wire everything up
@Module({ providers: [MiniEventBus, NotificationService] })
class AppModule {}
After app.init() returns, MiniEventBus.onReady() has already scanned every singleton, found NotificationService.sendWelcome via its @Fire('user.created') metadata, and subscribed it to the 'user.created' topic. Calling bus.emit('user.created', { id: 1 }) from anywhere in the app fires the handler. No registration list, no manual wiring - every @Fire-decorated method on every singleton just works.
Discovering controllers
DiscoveryService also powers class-level discovery. Every controller in the app carries a RESOLVED_PREFIX metadata entry - the fully-joined path under which its routes are served, including the prefix of every module it was imported through. getClassesWithMeta(RESOLVED_PREFIX) gives you a live map of controllers to their routing prefixes.
import { DiscoveryService, Injectable, RESOLVED_PREFIX, inject } from '@miiajs/core'
@Injectable()
export class RouteInspector {
private discovery = inject(DiscoveryService)
async onReady() {
for (const { ctor, metadata: prefix } of this.discovery.getClassesWithMeta<string>(RESOLVED_PREFIX)) {
console.log(`${ctor.name} -> /${prefix}`)
}
}
}
This is the call @miiajs/swagger uses internally to walk every controller and emit the OpenAPI spec. Any package that needs to enumerate live routes - metrics exporters, route tables, tracing instrumentation - can make the same call.
Registering routes in onReady
Router is injectable too, so a discovery-aware provider can both scan for metadata and register brand-new routes based on what it finds - all inside onReady(), before the HTTP server accepts its first request.
Exports
import {
DiscoveryService,
type DiscoverableMethodMeta,
type DiscoveredClass,
type DiscoveredMethod,
} from '@miiajs/core'