Ben Racicot
Ben Racicot

Reputation: 5915

@Inject services in other service - Nest can't resolve dependencies

I'm trying to @Inject two services into a NestJS service and am getting

Nest can't resolve dependencies of the MainServiceImpl (?, Symbol(MainDao)). Please make sure that the argument at index [0] is available in the MainModule context

Here is the service:

@Injectable()
export class MainServiceImpl implements MainService {

    constructor(
        @Inject(TYPES.PublishSubscriptionService) private publishSubscriptionService: PublishSubscriptionService,
        @Inject(TYPES.MainDao) private mainDao: MainDao
    ) {}

Now if I switch the order, it's always the second injected service that gets the error.

TYPES is an object of Symbols

const TYPES = {
    PublishSubscriptionService: Symbol('PublishSubscriptionService'),
    MainDao: Symbol('MainDao'),
};
export default TYPES;

Here is the index.ts which is using barreling

// start:ng42.barrel
export * from './main.dao.mongo-impl';
export * from './main.dao';
export * from './main';
export * from './main.schema';
export * from './main.service.impl';
export * from './main.service';
// end:ng42.barrel

What am I missing?

Closed NestJS issue with no resolution
NestJS doc on @Global modules

Upvotes: 2

Views: 2938

Answers (2)

Jay McDoniel
Jay McDoniel

Reputation: 70151

I can't say for sure without seeing your MainServieImplModule or whatever the module that contains this service is called, but if I had to guess, you are not declaring your providers to Nest correctly for these two services. You'll need to create a custom provider like so

@Module({
  provides: [
    {
      provide: TYPES.PublishSubscriptionService,
      useClass: PublishSubscriptionService,
    },
    {
      provide: TYPES.MainDao,
      useClass: MainDao
    },
    MainServiceImpl
  ]
})
export class MainServiceImplModule {}

If however, those providers are part of a different module you will need to make sure that the providers are custom (as above), but are also exported so they can be imported and used in a different module. Without seeing more of your code, the question is not possible to answer, but I think this should give you the direction you need. If not, please edit your question and add more information.

Upvotes: 2

tano
tano

Reputation: 2817

I don't know what TYPES is, you can use @Inject(PublishSubscriptionService) or you can use simply:

constructor(
        private publishSubscriptionService: PublishSubscriptionService,
        private mainDao: MainDao
) {}

Upvotes: 0

Related Questions