wiseindy
wiseindy

Reputation: 19655

NestJS: How to inject a service into a provider from the same module?

Is it possible to inject a service into a factory provider from the same module? I have a service AppService that I would like to use in this factory provider below.

Here is my code:

app.module.ts

@Module({
  imports: [
    MongooseModule.forFeatureAsync([
        {
            name: 'List',
            imports: [AnotherModule],
            useFactory: (anotherService: AnotherService) => {
                const schema = ListSchema;
                schema.pre('save', function() {
                    // Validate
                })
                return schema;
            },
            inject: [AnotherService],
        },
  ],
  providers: [AppService],
  exports: [AppService],
})
export class AppModule {}

I want to be able to do something like this:

app.module.ts

@Module({
  imports: [
    MongooseModule.forFeatureAsync([
        {
            name: 'List',
            imports: [AnotherModule, AppModule],
            useFactory: (anotherService: AnotherService, appService: AppService) => {
                const schema = ListSchema;
                schema.pre('save', function() {
                    // Validate
                })
                return schema;
            },
            inject: [AnotherService, AppService],
        },
  ],
  providers: [AppService],
  exports: [AppService],
})
export class AppModule {}

This does not work. Nest fails to initialize all dependencies and the application does not run.

Is it even possible to do something like this?

How can I inject a service from the same module into this factory provider? One solution would be to move that service to a different module and then inject that service. However, I would like to avoid that if possible.

Upvotes: 3

Views: 6101

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70131

It's not possible to add a service from the current module into a module that the current module imports as a part of it's bootstrap, as that would be a major circular dependency between the two. You may be able to get around it would some interesting forwardRef() functions, but overall, that kind of pattern should be avoided as it brings confusion into the codebase

Upvotes: 3

Related Questions