TypeDI
Search…
Creating custom decorators
NOTE: This page is a direct copy of the old documentation. It will be reworked.
You can create your own decorators which will inject your given values for your service dependencies. For example:
1
// Logger.ts
2
export function Logger() {
3
return function (object: Object, propertyName: string, index?: number) {
4
const logger = new ConsoleLogger();
5
Container.registerHandler({ object, propertyName, index, value: containerInstance => logger });
6
};
7
}
8
9
// LoggerInterface.ts
10
export interface LoggerInterface {
11
log(message: string): void;
12
}
13
14
// ConsoleLogger.ts
15
import { LoggerInterface } from './LoggerInterface';
16
17
export class ConsoleLogger implements LoggerInterface {
18
log(message: string) {
19
console.log(message);
20
}
21
}
22
23
// UserRepository.ts
24
@Service()
25
export class UserRepository {
26
constructor(@Logger() private logger: LoggerInterface) {}
27
28
save(user: User) {
29
this.logger.log(`user ${user.firstName} ${user.secondName} has been saved.`);
30
}
31
}
Copied!
Last modified 1mo ago
Copy link