The Service Container
Introduction
The service container is a registry that knows how to build the objects your application needs. Instead of constructing a database connection or a mailer wherever you need one, you tell the container once how to build it, and ask for it by name. This keeps wiring in one place, lets you swap an implementation for a fake in tests, and controls whether an object is created once or on every request.
The container lives in @plinthjs/core as the Container class. The Application is a container that also owns configuration and the provider lifecycle, so inside an app you work with app.bind(...) and app.make(...) directly.
pnpm add @plinthjs/coreTokens
Every binding has an identifier, called a token. A token is a string, a symbol, or a class:
import { Container } from '@plinthjs/core'
const container = new Container()
container.bind('rand', () => Math.random()) // a string token
container.bind(Symbol.for('app.db'), () => ({ connected: true })) // a symbol token
container.bind(Mailer, () => new Mailer()) // a class used as a tokenSymbols avoid collisions between packages. The generated app uses them for its own bindings, for example export const DB = Symbol.for('app.db') in src/providers/app-service-provider.ts, and resolves them with app.make<Connection>(DB).
INFO
JavaScript has no way to read constructor parameter types at runtime, so the container does not autowire dependencies. You write the wiring yourself in a factory function, which keeps it explicit and type-checked.
Binding
Simple bindings
bind registers a factory that runs every time the token is resolved. The factory receives the container and any parameters passed to make:
class Mailer {
host: string
constructor(host = 'localhost') {
this.host = host
}
}
container.bind(Mailer, (c, params) => new Mailer(String(params['host'] ?? 'smtp')))
container.make(Mailer, { host: 'mx' }) // => Mailer { host: 'mx' }
container.make(Mailer) // => Mailer { host: 'smtp' }You can pass a class instead of a factory. The container constructs it with no arguments, which is a convenient way to bind a contract to an implementation:
interface Store {
get(key: string): string | undefined
}
class FileStore implements Store {
get(key: string): string | undefined {
return undefined
}
}
container.bind<Store>('store', FileStore)
container.make<Store>('store') // => FileStore {}A plain function is treated as a factory and a class (declared with the class keyword) is treated as something to construct. A class token with no binding at all is constructed directly the first time you resolve it, and you can hand it constructor arguments through params.args:
container.make(Mailer, { args: ['smtp.example.com'] }) // => Mailer { host: 'smtp.example.com' }bindIf registers a binding only when nothing is registered for the token yet, which lets a package provide a default that your app can override:
container.bindIf('rand', () => 1) // ignored if 'rand' is already boundSingletons
singleton is bind with caching: the factory runs once, and every later make returns the same object. Use it for things that hold a connection or are expensive to build:
container.singleton('conn', () => ({ id: Math.random() }))
container.make('conn') === container.make('conn') // => truesingletonIf is the "only if unbound" variant. When the factory returns a value, the container keeps that exact value. To register an object you have already built, use instance:
container.instance('config', { debug: true })
container.make('config') // => { debug: true }Scoped bindings
A scoped binding behaves like a singleton until the scope ends. scoped registers one, and forgetScopedInstances drops every cached scoped object so the next make rebuilds it:
let n = 0
container.scoped('cart', () => ({ id: ++n }))
container.make('cart').id // => 1
container.make('cart').id // => 1 (cached)
container.forgetScopedInstances()
container.make('cart').id // => 2 (rebuilt)Scoped bindings exist for long-lived processes. The persistent server in @plinthjs/cluster calls forgetScopedInstances() after every request so per-request services do not leak into the next one. The plain HttpKernel does not call it for you, so if you rely on scoped bindings with the default server, call it yourself at the end of a request. scopedIf is the "only if unbound" variant.
Aliases
alias(abstract, alias) makes a second name resolve to an existing binding:
container.alias('conn', 'db')
container.make('db') === container.make('conn') // => trueAliases can chain, and an alias to itself throws.
Checking and removing
container.bound('db') // => true (also true for aliases and instances)
container.has('nope') // => false
container.forget('rand') // remove the binding and any cached instance
container.forgetInstance('conn') // drop only the cached instance, keep the binding
container.flush() // empty the container entirelyResolving
make returns the object for a token. Pass the type you expect, since a token does not carry its type:
const db = container.make<Connection>(DB)Resolving a token that has no binding and is not a class throws a BindingResolutionError. makeOr returns a default instead:
import { BindingResolutionError } from '@plinthjs/core'
try {
container.make('missing')
} catch (error) {
error instanceof BindingResolutionError // => true
// "No binding registered for [missing] and it is not constructable."
}
container.makeOr('missing', 'fallback') // => 'fallback'factory gives you a function that resolves the token afresh each time you call it, which is handy for passing a lazy dependency:
const nextRand = container.factory<number>('rand')
nextRand()The Application registers itself and its config in the container, so you can resolve them like any other service:
import { APP, Application, CONFIG, Config } from '@plinthjs/core'
const app = new Application()
app.make(APP) === app // => true
app.make(Application) === app // => true
app.make(CONFIG) === app.config // => true
app.make(Config) === app.config // => trueResolving other services inside a factory
A factory receives the container, so one binding can depend on another:
container.singleton('mailer', (c) => new SmtpMailer(c.make('config')))The generated AuthServiceProvider does the same thing: it binds the user provider using this.app.make(DB) and this.app.make(HASHER).
Calling a method with the container
call invokes a closure or a method on a class, passing a parameter object and the container. It is the container's way to run a piece of code with access to everything it knows about:
container.call(({ id }, c) => `id=${id} has db: ${c.bound(DB)}`, { id: 5 })
// => 'id=5 has db: true'
class Reports {
run(params: Record<string, unknown>) {
return `ran ${String(params['name'])}`
}
}
container.call([Reports, 'run'], { name: 'daily' }) // => 'ran daily'With a [Class, 'method'] pair, the container resolves the class first (building it if needed), then calls the method as method(params, container). You can also pass an object instance instead of a class: container.call([service, 'run'], params). Because JavaScript cannot inspect parameter names, the callee reads what it needs from params rather than receiving individual arguments.
Contextual bindings
Sometimes two classes need different implementations of the same token. when(...).needs(...).give(...) binds a token differently depending on who is being built:
class PhotoStore {
disk: Disk
constructor(disk: Disk) {
this.disk = disk
}
}
class VideoStore {
disk: Disk
constructor(disk: Disk) {
this.disk = disk
}
}
container.instance('disk.local', { name: 'local' })
container.instance('disk.s3', { name: 's3' })
container.bind(PhotoStore, (c) => new PhotoStore(c.make('disk')))
container.bind(VideoStore, (c) => new VideoStore(c.make('disk')))
container.when(PhotoStore).needs('disk').give('disk.local')
container
.when(VideoStore)
.needs<Disk>('disk')
.give((c) => c.make<Disk>('disk.s3'))
container.make(PhotoStore).disk.name // => 'local'
container.make(VideoStore).disk.name // => 's3'give accepts another token (resolved through the container), a factory function, or a plain value. when also accepts an array of classes to give several consumers the same override. The override applies while the named class is being built, so the factory must call c.make('disk') during construction, as above.
Tagging
tag groups several tokens under a name, and tagged resolves them all at once. Use it to collect a family of services such as report generators or health checks:
container.bind('report.sales', () => 'sales')
container.bind('report.stock', () => 'stock')
container.tag(['report.sales', 'report.stock'], 'reports')
container.tagged('reports') // => ['sales', 'stock']
container.tagged('unknown') // => []A token can be listed under several tags with container.tag(id, 'a', 'b').
Extending and observing resolution
Extending a binding
extend wraps a service with a decorator. The callback receives the resolved object and returns what should be used instead:
container.singleton('clock', () => ({ now: () => 1 }))
container.extend<{ now(): number }>('clock', (clock) => ({ now: () => clock.now() + 100 }))
container.make<{ now(): number }>('clock').now() // => 101If the singleton was already resolved, it is decorated immediately and the decorated value replaces the cached one. References you obtained before the call are not changed.
Resolving callbacks
Callbacks let you react as objects are built. resolving (or its alias afterResolving) runs after an object is built, and beforeResolving runs before, receiving the parameters. Pass a token to target one binding, or omit it to observe every resolution:
container.resolving('svc', (service, c) => {
service.ready = true
})
container.beforeResolving('svc', (params) => {
console.log('about to build svc', params)
})
container.resolving((object) => {
// runs for every token
})Rebinding
When a token is bound again after it was already bound, rebinding callbacks run with the new value. This keeps a long-lived object up to date when a dependency is swapped:
container.singleton('mailer', () => ({ v: 1 }))
container.rebinding('mailer', (mailer) => console.log('rebound', mailer))
container.singleton('mailer', () => ({ v: 2 })) // logs: rebound { v: 2 }refresh wires this up for you. It pushes the current value into a target object through a method (or property), and does so again on every future rebind:
const holder = {
mailer: container.make<{ v: number }>('mailer'),
setMailer(mailer: { v: number }) {
this.mailer = mailer
},
}
container.refresh('mailer', holder, 'setMailer')
container.singleton('mailer', () => ({ v: 3 }))
holder.mailer // => { v: 3 }Testing with the container
Because services are resolved by token, replacing one for a test is a single call. instance overrides whatever was bound, so a test can drop in a fake:
container.singleton('cache', () => ({ kind: 'real' }))
container.instance('cache', { kind: 'fake' })
container.make('cache') // => { kind: 'fake' }A fresh Container or Application per test gives you isolation without cleanup. Facades give you the same ability through a static-looking API; see Facades.
Programming against contracts
Services can describe the shape they need with an interface from @plinthjs/contracts instead of importing a concrete package. The container's own shape is available there too, so code that only needs to resolve things can depend on a small interface:
import type { CacheRepository } from '@plinthjs/contracts'
class ReportService {
private readonly cache: CacheRepository
constructor(cache: CacheRepository) {
this.cache = cache
}
}
container.bind(ReportService, (c) => new ReportService(c.make('cache')))Where bindings live
By convention, bindings are registered in a service provider's register method, so they all exist before anything is resolved. A controller that you route to is also resolved through the container on each request; see The Request Lifecycle.