嵌套。自定义提供程序,注入无法解析 useFactory 的依赖项
NestJS. Custom provider, inject can't resolve dependencies of the useFactory
我在应用程序启动期间收到以下错误:
Error: Nest can't resolve dependencies of the useFactory (?). Please verify whether [0] argument is available in the current context.
ConfigService
被导出并且 ConfigModule
作为第一个模块加载。不知道是我的错还是 NestJS 中的错误。
也许有人可以找到一些东西)谢谢。
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],
},
];
部分 app.module.ts:
@Module({
imports: [
ConfigModule,
DatabaseModule,
GraphQLModule,
UsersModule,
],
exports: [DatabaseModule],
})
部分 config.module.ts:
@Module({
providers: [
{
provide: ConfigService,
useValue: new ConfigService(`./config`),
},
],
exports: [ConfigService],
})
您必须在 DatabaseModule
中导入 ConfigModule
。默认情况下,Nest 中的提供程序不是全局范围的。
我在应用程序启动期间收到以下错误:
Error: Nest can't resolve dependencies of the useFactory (?). Please verify whether [0] argument is available in the current context.
ConfigService
被导出并且 ConfigModule
作为第一个模块加载。不知道是我的错还是 NestJS 中的错误。
也许有人可以找到一些东西)谢谢。
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],
},
];
部分 app.module.ts:
@Module({
imports: [
ConfigModule,
DatabaseModule,
GraphQLModule,
UsersModule,
],
exports: [DatabaseModule],
})
部分 config.module.ts:
@Module({
providers: [
{
provide: ConfigService,
useValue: new ConfigService(`./config`),
},
],
exports: [ConfigService],
})
您必须在 DatabaseModule
中导入 ConfigModule
。默认情况下,Nest 中的提供程序不是全局范围的。