Nestjs:避免在服务的构造函数中重复表达
Nestjs: avoid repetitive expression in constructor of service
在 NestJs 中我有这个构造函数:
@Injectable()
export class DummyService {
constructor(
private readonly logger: LoggerService,
private readonly config: ConfigService,
private readonly session: SessionService,
private readonly core: CoreService,
private readonly tracking: TrackingService,
) {
this.logger.setContext(this.constructor.name);
}
}
这一行:
this.logger.setContext(this.constructor.name);
...让我很无聊,因为每项服务都需要它。
我想添加装饰器 (@LogContext()) 或...其他东西来避免这一行。
像 :
@LogContext(LoggerService)
@Injectable()
export class DummyService {
constructor(
private readonly config: ConfigService,
private readonly session: SessionService,
private readonly core: CoreService,
private readonly tracking: TrackingService,
) {}
}
但是我不知道该怎么做。
注意:通过继承是做不到的,Dependency Injection拒绝继承。
技术上你可以通过依赖注入来继承,在这种情况下它不会改变太多。我在自定义记录器中所做的是创建一个 LoggerModule.forFeature(FeatureClass.name)
,我在其中创建一个新的注入令牌,然后使用 @InjectLogger(FeatureClass.name)
注入指定的记录器。这允许减少代码中的重复(尽管从技术上讲,元仍在复制自身)。
我具体谈论的记录器包是 Ogma,我确保我在开发它时考虑到了 Nest 的 DI 系统。
在 NestJs 中我有这个构造函数:
@Injectable()
export class DummyService {
constructor(
private readonly logger: LoggerService,
private readonly config: ConfigService,
private readonly session: SessionService,
private readonly core: CoreService,
private readonly tracking: TrackingService,
) {
this.logger.setContext(this.constructor.name);
}
}
这一行:
this.logger.setContext(this.constructor.name);
...让我很无聊,因为每项服务都需要它。
我想添加装饰器 (@LogContext()) 或...其他东西来避免这一行。 像 :
@LogContext(LoggerService)
@Injectable()
export class DummyService {
constructor(
private readonly config: ConfigService,
private readonly session: SessionService,
private readonly core: CoreService,
private readonly tracking: TrackingService,
) {}
}
但是我不知道该怎么做。 注意:通过继承是做不到的,Dependency Injection拒绝继承。
技术上你可以通过依赖注入来继承,在这种情况下它不会改变太多。我在自定义记录器中所做的是创建一个 LoggerModule.forFeature(FeatureClass.name)
,我在其中创建一个新的注入令牌,然后使用 @InjectLogger(FeatureClass.name)
注入指定的记录器。这允许减少代码中的重复(尽管从技术上讲,元仍在复制自身)。
我具体谈论的记录器包是 Ogma,我确保我在开发它时考虑到了 Nest 的 DI 系统。