Skip to content

Function: Lifetime() ​

Lifetime<ClassConstructor>(lifetime, lock?): ClassDecorator<ClassConstructor>

Set how the container shares the instances of a class: SINGLETON (one instance, created once by the container registering the class and shared by all its users), SCOPED (one instance per scope, a request of an entrypoint), or TRANSIENT (a new instance on each request, never cached). Subclasses inherit the lifetime. BaseObject is transient, Provider scoped (a provider may be a singleton, scoped or transient), Component and Module are locked singletons. Prefer the shorthands @Singleton(), @Scoped() and @Transient().

Type Parameters ​

ClassConstructor ​

ClassConstructor extends typeof BaseObject

Parameters ​

lifetime ​

LifetimeType

The lifetime: 'SINGLETON', 'SCOPED' or 'TRANSIENT'.

lock? ​

boolean

Whether the subclasses are forbidden to change the lifetime (they may still declare the same one). Default false.

Returns ​

ClassDecorator<ClassConstructor>

The class decorator.

Throws ​

When the class is defined, if a parent class locked another lifetime.

Example ​

typescript
import {BaseObject} from 'lakutata'
import {Lifetime} from 'lakutata/decorator/di'

//A new counter for each object requesting it
@Lifetime('TRANSIENT')
export class Counter extends BaseObject {
    public value: number = 0
}

Released under the MIT License.