Transient
Scope-modifier decorator. Defines a provider as @transient
, ensuring a new
instance each time the provider is injected.
By default, providers are singletons, meaning a single instance is reused.
With @transient
, a new instance is created upon each injection, which is
useful for stateless or temporary dependencies.
Comparing @transient
vs @isolated
:
@transient
creates a new instance each time it’s requested.@isolated
creates one instance per context (“different context, different instance”).
import {
application,
Context,
contextualize,
provide,
provider,
transient,
} from 'aspectra'
import { randomUUID } from 'node:crypto'
@transient
@provider
class Logger {
public readonly id = randomUUID()
}
@application
class Application {
@provide(Logger)
private readonly first!: Logger
@provide(Logger)
private readonly second!: Logger
@provide(Logger)
private readonly third!: Logger
public start() {
console.table({
first: this.first.id,
second: this.second.id,
third: this.third.id,
})
}
}
[auto-generated] output:
┌─────────┬────────────────────────────────────────┐
│ (index) │ Values │
├─────────┼────────────────────────────────────────┤
│ first │ 'cf9be6b5-2d8a-4290-a006-89ab16c59110' │
│ second │ '9d1f9fdd-fd19-4cb1-a863-dfdc1a43c212' │
│ third │ 'e176b823-1d17-410f-bc9b-365c6bd97b50' │
└─────────┴────────────────────────────────────────┘
Last updated on