NestJS可以实现这种依赖注入吗?

时间:2019-07-16 11:26:40

标签: dependency-injection decorator nestjs

我想简单地将Nest服务方法的结果作为依赖项注入。示例是一个日志记录工具,其中子记录器是从主记录器派生的,并带有新的前缀。

应该是这样的(长版):

@Injectable()
class MyService {
  private logger;

  constructor(private loggerService: LoggerService) {
    this.logger = loggerService.getChildLogger('prefix');
  }

  someMethod() {
    this.logger.info('Hello');
  }  
}

但是在简短的版本中,可能是这样-可能带有装饰器:

@Injectable()
class MyService {
  constructor(@logger('prefix') logger: LoggerService) {
  }

  someMethod() {
    this.logger.info('Hello');
  }  
}

2 个答案:

答案 0 :(得分:0)

您可以使用工厂注入LoggerService来为记录器创建提供程序:

LoggerService

@Injectable()
export class LoggerService {
  getChildLogger(scope: string) {
    return new Logger(scope);
  }
}

MyService

@Injectable()
export class MyService implements OnModuleInit {
  constructor(@Inject('MY_SERVICE_LOGGER_TOKEN') public childLogger) {}

  onModuleInit() {
    this.childLogger.log('Hello World');
  }
}

模块:

@Module({
  providers: [
    LoggerService,
    MyService,
    {
      provide: 'MY_SERVICE_LOGGER_TOKEN', 
      useFactory: (loggerService) => loggerService.getChildLogger('scope'), 
      inject: [LoggerService]
    },
  ]
})
export class MyModule {}

答案 1 :(得分:0)

Livio Brunner现在提供了一个解决方案: https://github.com/BrunnerLivio/nestjs-logger-decorator