Injectable Decorator
The @Injectable
decorator is a key feature of Depinjionary. It is used to mark a class as a dependency that the container can register and manage.
Features
- Automatic Registration: Marks a class as a dependency for the container.
- Singleton by Default: Dependencies are registered as singletons by default, ensuring one shared instance across the application.
- Transient Option: Optionally specify a dependency as transient to create a new instance each time it is resolved.
Usage
Default Singleton Dependency
By default, the @Injectable
decorator registers the class as a singleton:
import { Injectable } from "depinjionary";
@Injectable()
export class CalculatorService {
calculate(a: number, b: number): number {
return a + b;
}
}
Transient Dependency
To resolve a dependency as transient, specify the type
option with Type.TRANSIENT
:
import { Injectable, Type } from "depinjionary";
@Injectable({ type: Type.TRANSIENT })
export class CalculatorService {
calculate(a: number, b: number): number {
return a + b;
}
}
Options
The @Injectable
decorator accepts the following configuration options:
Option | Type | Default | Description |
---|---|---|---|
type | Type | Type.SINGLETON | Defines the lifecycle of the dependency. Use Type.TRANSIENT for a transient lifecycle. |
Requirements
To use the @Injectable
decorator, experimental decorator support must be enabled in your TypeScript configuration. Add the following to your tsconfig.json
:
{
"compilerOptions": {
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}
Example
Here's an example that combines the @Injectable
decorator with ContainerResolver
to register and resolve dependencies:
import { Injectable, ContainerResolver, ContainerInterface } from "depinjionary";
@Injectable()
export class CalculatorService {
calculate(a: number, b: number): number {
return a + b;
}
}
const providers = [{ provide: CalculatorService }];
const container: ContainerInterface = ContainerResolver.init(providers);
const calculator = await container.resolve<CalculatorService>(CalculatorService);
console.log(calculator.calculate(5, 10)); // Outputs: 15
Notes
- Ensure
experimentalDecorators
andemitDecoratorMetadata
are enabled in yourtsconfig.json
file. - The singleton type is suitable for shared services, while transient is ideal for stateless or short-lived dependencies.