Nest 找不到 PrismaService 元素(当前上下文中不存在此提供程序)

Raf*_*iro 2 nestjs prisma

我试图在我的 main.ts 上获取 PrismaService,但它一直崩溃。我是新手,谁能帮我解决这个问题?我的 prisma.service.ts:

import { INestApplication, Injectable, OnModuleInit } from '@nestjs/common';
import { PrismaClient } from '@prisma/client';

@Injectable()
export class PrismaService extends PrismaClient implements OnModuleInit {
  async onModuleInit() {
    await this.$connect();
  }

  async enableShutdownHooks(app: INestApplication) {
    this.$on('beforeExit', async () => {
      await app.close();
    });
  }
}
Run Code Online (Sandbox Code Playgroud)

我的主要.ts:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { PrismaService } from './prisma.service';
import { ValidationPipe } from '@nestjs/common';
import helmet from 'helmet';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  app.enableCors({
    allowedHeaders: '*',
    origin: '*',
  });
  app.use(helmet());
  app.use(helmet.hidePoweredBy());
  app.use(helmet.contentSecurityPolicy());

  const prismaService = app.get(PrismaService);
  await prismaService.enableShutdownHooks(app);

  app.useGlobalPipes(
    new ValidationPipe({
      transform: true,
      whitelist: true,
      forbidNonWhitelisted: true,
    }),
  );

  await app.listen(process.env.PORT, () => console.log('runing...'));
}
bootstrap();
Run Code Online (Sandbox Code Playgroud)

错误信息:

Error: Nest could not find PrismaService element (this provider does not exist in the current context)
    at InstanceLinksHost.get (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/injector/instance-links-host.js:15:19)
    at NestApplication.find (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/injector/abstract-instance-resolver.js:8:60)
    at NestApplication.get (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-application-context.js:64:20)
    at /home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:133:40
    at Function.run (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/errors/exceptions-zone.js:10:13)
    at Proxy.<anonymous> (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:132:46)
    at Proxy.<anonymous> (/home/rafittu/wophi/alma/back/node_modules/@nestjs/core/nest-factory.js:181:54)
    at bootstrap (/home/rafittu/wophi/alma/back/src/main.ts:18:29)
Run Code Online (Sandbox Code Playgroud)

当我从 main.ts 中删除 PrismaService 时,服务器正常启动

Jay*_*iel 6

使用app.get(PrismaService, { strict: false })。也就是说不直接提供provider而要遍历DI容器来找到strict: falseAppModule

  • 您是否有一个模块包含由“AppModule”导入的“providers: [PrimsaService]”? (4认同)