首页 > 解决方案 > nestjs and typeorm - failing to setup the dependency injection

问题描述

I am trying to use nestjs and typeorm to write a basic CRUD application working but I am failing to get the dependency injection working. I am trying to put the code setups the database into separate modules and import it.

This is the error I am getting:

[ExceptionHandler] Nest can't resolve dependencies of the QuestionController (?). Please make sure that the argument at index [0] is available in the current context. +14ms 4: v8::internal::MaybeHandle v8::internal::(anonymous namespace)::HandleApiCallHelper(v8::internal::Isolate*, v8::internal::Handle, v8::internal::Handle, v8::internal::Handle, v8::internal::Handle, v8::internal::BuiltinArguments) [/usr/local/bin/node]

This is the basic code structure:

database.module.ts

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: 'sqlite',
      database: 'database.sqlite',
    }),
  ],
})
export class DatabaseModule {
}

question.module.ts:

@Module({
  imports: [
    DatabaseModule,
    TypeOrmModule.forFeature([Question]),
  ],
  providers: [QuestionDal, QuestionLogic],
})
export class QuestionModule {
}

app.module.ts

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

question.dal.ts

@Injectable()
export class QuestionDal {

  constructor(@InjectRepository(Question) private questionRepo: Repository<Question>) { }

}

question.logic.ts

@Injectable()
export class QuestionLogic {
  constructor(private questionDal: QuestionDal) { }
}

question.controller.ts

@Controller()
export class QuestionController {
  constructor(private readonly appService: QuestionLogic) { }

}

I appreciate any help or hint

标签: typescriptdependency-injectionnestjs

解决方案


You have to export the QuestionLogic provider inside the QuestionModule.

You will be able to inject it in others modules importing the QuestionModule.

@Module({
  imports: [
    DatabaseModule,
    TypeOrmModule.forFeature([Question]),
  ],
  providers: [QuestionDal, QuestionLogic],
  exports: [QuestionLogic] 
})
export class QuestionModule {
}

推荐阅读