I’m running into a very troubling issue with NestJS and dependency injection.
Here is my NestJS Controller:
import { Controller, Get } from '@nestjs/common'
import { TestService } from './TestService.service'
@Controller()
export class TestController {
constructor(private testService: TestService) {}
@Get('join')
join() {
this.service.foo()
return 'success'
}
}
Here is my NestJS Service:
import { Injectable } from '@nestjs/common'
@Injectable()
export class TestService {
foo() {
console.log('foo')
}
}
Here is my AppModule:
@Module({
providers: [
TestService,
],
controllers: [
TestController,
],
})
export class AppModule {}
Calling the above route throws an error:
TypeError: Cannot read properties of undefined (reading 'foo')
If I annotate the controller with property injection like so:
import { Controller, Get, Inject } from '@nestjs/common'
import { TestService } from './TestService.service'
@Controller()
export class TestController {
@Inject(TestService) // <----- HERE
constructor(private testService: TestService) {}
@Get('join')
join() {
this.service.foo()
return 'success'
}
}
Then the call is a success. It would seem that without property-based injection, Nest DI isn’t registering my service.
Any ideas what could be wrong here?
NestJS deps:
"@nestjs/common": "^10.3.8",
"@nestjs/core": "^10.3.7",
"@nestjs/platform-express": "^10.3.7",