NestJS. Custom provider, inject can't resolve dependencies of the useFactory
12,398
You have to import ConfigModule
inside your DatabaseModule
. The providers in Nest aren't globally scoped by default.
Related videos on Youtube
Author by
Vladyslav Moisieienkov
Updated on June 04, 2022Comments
-
Vladyslav Moisieienkov almost 2 years
I get the following error during app start:
Error: Nest can't resolve dependencies of the useFactory (?). Please verify whether [0] argument is available in the current context.
ConfigService
is exported andConfigModule
is loaded as first module. Don't know if it's my fault or it's a bug in NestJS. Maybe somebody could find something) Thank you.database.providers.ts:
import { Sequelize } from 'sequelize-typescript'; import { SEQUELIZE_TOKEN } from './constants'; import { User } from '../users/user.entity'; import { ConfigService } from '../config/config.service'; export const databaseProviders = [ { provide: SEQUELIZE_TOKEN, useFactory: async (configService: ConfigService) => { const sequelize = new Sequelize({ dialect: 'mysql', host: 'localhost', port: 3306, username: configService.databaseUser, password: configService.databasePassword, database: configService.databaseName, operatorsAliases: false, logging: false, }); sequelize.addModels([User]); await sequelize.sync({ force: process.env.NODE_ENV === 'local' || process.env.NODE_ENV === 'test', }); return sequelize; }, inject: [ConfigService], }, ];
Part app.module.ts:
@Module({ imports: [ ConfigModule, DatabaseModule, GraphQLModule, UsersModule, ], exports: [DatabaseModule], })
Part config.module.ts:
@Module({ providers: [ { provide: ConfigService, useValue: new ConfigService(`./config`), }, ], exports: [ConfigService], })
-
Vladyslav Moisieienkov almost 6 yearsThank you, works perfectly. Maybe add information about scope of providers to official docs (custom providers section)?
-
mudassirijaz786 over 3 yearsYes, there are many custom decorators techniques available to follow. Reading out this in 2021 :).