谁能帮我理解 DI Nest Fundamentals,我的问题:
“是否可以有一个服务类没有@Injectable注解,而且这个类不属于任何模块?”我在网上看到一个例子如下:
此类存在于公共文件夹中:
export class NotificationService {
constructor(
@Inject(Logger) private readonly logger: LoggerService,
private readonly appConfigService: AppConfigService,
@Inject(HttpService) private readonly httpService: HttpService
) {}
async sendNotification(msg: string) {
....
}
}
然后在providers数组中的另一个模块中注册:
import { Module, Logger, forwardRef, HttpModule } from '@nestjs/common';
import { MongooseModule } from '@nestjs/mongoose';
import { NotificationService } from '../../commons/notification/notification.service';
@Module({
imports: [
...
],
controllers: [InvoiceController],
providers: [
InvoiceService,
NotificationService,
Logger],
exports: [InvoiceService]
})
export class InvoiceModule { }
然后被注入到其他服务的构造方法中
@Injectable()
export class InvoiceService {
constructor(
@Inject(Logger) private readonly logger: LoggerService,
private readonly notificationService: NotificationService) { }
...
}
这很好用,但我不知道为什么。为什么通知服务没有加@Injectable,也没有和import模块就被正确注入了?
答案 0 :(得分:3)
那么让我们分解一下 @Injectable()
装饰器的实际情况。
通常,我们使用装饰器来设置关于我们正在装饰的类、参数、方法或属性的元数据,或者我们使用它通过描述符以某种方式修改方法(如果是方法装饰器)或属性(属性装饰器) .在 @Injectable()
的情况下,我们并没有真正做这些。当然我们是 setting the scope metadata,但这似乎并没有真正设置任何关于“嘿,这个类可以通过 Nest 框架注入”的元数据。这是因为 @Injectable()
真正为我们设置的是 tsconfig
和 tsc
编译器的特殊属性,即 emitDecoratorMetadata
属性。有了这个属性,typescript 会在文件的开头和结尾添加一堆额外的函数。这些函数一般是这样的
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
和
DelegatorService = __decorate([
common_1.Injectable(),
__metadata("design:paramtypes", [http_interceptor_service_1.HttpInterceptorService,
websocket_interceptor_service_1.WebsocketInterceptorService,
rpc_interceptor_service_1.RpcInterceptorService,
gql_interceptor_service_1.GqlInterceptorService])
], DelegatorService);
这是非常重要的部分,因为这 "design:paramtypes"
实际上是 Nest 在确定要注入的内容时所读取的内容。
只有在类中的任何地方使用装饰器时,此元数据才可用,并且有 was actually an eslint-typescript discussion 关于元数据以及 import type
如何破坏它,以及 a recent PR 真正进入杂草丛生。
我提出所有这些是为了说,因为您在构造函数中有 @Inject()
,所以 @Injectable()
实际上是无关紧要的,除非您要设置范围级别的元数据,否则没有必要。类型元数据将被发出,因此这解释了为什么您不需要 @Injectable()
(尽管我仍然认为拥有它是一个好主意,因为它提供了明确的意图)。
现在为什么注入正常工作,我保证这个不那么复杂:您将 NotificationsService
添加到 InvoiceModule
的
providersarray. This tells Nest that any service inside of
InvoiceModule{{ 1}}NotificationsService`,因此可以毫无问题地注入这里。