Nest: Cannot inject request to request-scoped service with moduleRef resolve method

Created on 25 Jun 2020  路  5Comments  路  Source: nestjs/nest

Bug Report

Current behavior

I cannot inject Request into service with moduleRef resolve method. The request object is always undefined. I'd like to inject request-scoped service into singleton-scoped controller.

Input Code

app.service.ts

import { Injectable, Scope, Inject } from '@nestjs/common';
import { REQUEST } from '@nestjs/core'

@Injectable({ scope: Scope.REQUEST })
export class AppService {

  constructor(@Inject(REQUEST) request: any) {
    console.log(request) //undefined
  }

  getHello(): string {
    return 'Hello World!';
  }
}

app.controller.ts

import { Controller, Get } from '@nestjs/common';
import { ModuleRef } from '@nestjs/core';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly moduleRef: ModuleRef) {}

  @Get()
  async getHello(): Promise<string> {
    return (await this.moduleRef.resolve(AppService)).getHello()
  }
}

app.module.ts

import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';

@Module({
  imports: [],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

Environment


"@nestjs/common": "^7.0.0",
"@nestjs/core": "^7.0.0",
"@nestjs/platform-express": "^7.0.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^6.5.4"
needs triage

Most helpful comment

We've added the registerRequestByContextId() method to the ModuleRef in 7.3.0 release. Example

const contextId = ContextIdFactory.create();
this.moduleRef.registerRequestByContextId(YOUR_REQUEST_OBJECT, contextId);
const appService = await this.moduleRef.resolve(AppService, contextId);

All 5 comments

@kamilmysliwiec please, take a look. I can't go further with my work :(

Please provide a minimum reproduction Repository. We are working through bugs as we can

Please provide a minimum reproduction Repository.

https://github.com/piotr-pawlowski/nestjs-inject-request-issue

We've added the registerRequestByContextId() method to the ModuleRef in 7.3.0 release. Example

const contextId = ContextIdFactory.create();
this.moduleRef.registerRequestByContextId(YOUR_REQUEST_OBJECT, contextId);
const appService = await this.moduleRef.resolve(AppService, contextId);

Does it work with GraphQL Context as well? I mean injecting a context: @Inject(CONTEXT) and a request: @Inject(REQUEST).

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rafal-rudnicki picture rafal-rudnicki  路  3Comments

marshall007 picture marshall007  路  3Comments

janckerchen picture janckerchen  路  3Comments

menme95 picture menme95  路  3Comments

2233322 picture 2233322  路  3Comments