简体   繁体   English

是否可以将在 main.ts 中创建的 NestJS 应用程序注入到模块服务中?

[英]Is it possible to Inject the NestJS app created in main.ts into a module service?

Assuming you have the basic NestJS setup:假设你有基本的 NestJS 设置:

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

  app.enableCors(corsOptions);

  app.useGlobalPipes(
    new ValidationPipe({
      validateCustomDecorators: true,
      transform: true,
      whitelist: true,
      exceptionFactory: exceptionFactory,
    }),
  );
  app.useGlobalFilters(new CustomExceptionsFilter());

  const port = parseInt(process.env.PORT);
  await app.listen(port);
}

Can I access the app variable created with NestFactory from a service in a different module?我可以从不同模块中的服务访问使用 NestFactory 创建的app变量吗?

@Injectable()
export class TestService {
  constructor(
    ...
  ) {}

  async useApp(): Promise<any> {
    const app = ... // use Injected app instance created from AppModule
  }

I've tried importing AppModule and creating a NestFactory again, but it just resolves into redundancies.我已经尝试导入 AppModule 并再次创建 NestFactory,但它只是解析为冗余。

NestFactory.create will create the app , which depends on modules & their providers. NestFactory.create将创建app ,这取决于模块及其提供者。 Using app before it has been created does not make sense.在创建app之前使用它是没有意义的。


Instead, you could tell us what you're trying to do with that app at TestService .相反,您可以在TestService告诉我们您尝试使用该app做什么。

There is no way to get the app instance itself from the Nest containers, you could simply export the app once it is created by NestFactory.create() .无法从 Nest 容器中获取app实例本身,您可以在应用程序由NestFactory.create()创建后简单地导出应用程序。

However, if you're looking for the instance of AppModule , this bellow snippet might help you.但是,如果您正在寻找AppModule的实例,下面的代码片段可能会对您有所帮助。

const app = await NestFactory.createApplicationContext(AppModule);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM