0

I'm trying to use nest custom provider with factory, for some reason I'm struggling to get it working. I've created the following sample -


interface ProviderOptions: {x:string, y:number};
interface AsyncProps {useFactory:(...args:any[])=> ProviderOptions, inject:any[], imports:any[] }

@Module({})
export class MyModule {
    
   static forRootAsync(asyncProps: AsyncProps): DynamicModule {
        
     const myFactory: Provider = {
          provide: "MY_PROVIDER",
          useFactory: asyncProps.useFactory,
          inject: asyncProps.inject,
        };
    
     return {
        module: MyModule,
        providers: [myFactory, MyService],
        exports: [MyService],
        imports: [...asyncProps.imports],
        };
    }
}

@Injectable()
export class MyService {

   constructor(@Inject("MY_PROVIDER") this options:ProviderOptions){

   }
}

For some reason I'm unable to resolve MyService -

Error: Nest can't resolve dependencies of the MyService (?). Please make sure that the argument dependency at index [0] is available in the MyModule context.

what I'm missing here?

Thanks!

UPDATE - so now it's really strange - originally MyService was in a different file, next to MyModule. when moved MyService to the same file as MyModule, the above code does work as expected. how can it be?

Asaf
  • 153
  • 2
  • 7
  • How are you using the `MyService` in the consuming module? – Jay McDoniel Apr 22 '21 at 22:10
  • @JayMcDoniel I'm injecting it via the constructor. however even without consuming it at all - Nest failed to load since he cant resolve the MyService dependency. – Asaf Apr 22 '21 at 22:17
  • But what does the consuming code of this look like? What's the full error? There's isn't enough here to know what's wrong – Jay McDoniel Apr 22 '21 at 22:21
  • @JayMcDoniel updated inline. Also now this code works when moving the class to the same file as the module. Do you have any explanation for that? – Asaf Apr 22 '21 at 22:45

1 Answers1

3

Based on your error, you have a circular file import which means that typecript can't resolve the class name and in turn Nest can't create the class. I just answered another question on it here

Jay McDoniel
  • 57,339
  • 7
  • 135
  • 147
  • Thanks! it does looks like it. "MY_PROVIDER" was a const in the module file, so the service file had a reference to that file. moving the token to const file solved the issue. – Asaf Apr 22 '21 at 22:56