monkeyUser
monkeyUser

Reputation: 4679

Nestjs import service or the whole module

I'm new in Nestjs, and I don't understand when I need to import the whole module or only the service if I want to Inject in another module.

For example: I have my loggingModule

import { Module } from "@nestjs/common";
import { LoggingService } from "./logging.service";

@Module({
    providers: [LoggingService],
    exports: [LoggingService],
})
export class LoggingModule {}

with my logginService:

import { Injectable } from "@nestjs/common";

@Injectable()
export class LoggingService {

    logToConsole(logString: string) {
        console.log(logString)
    }
}

I want to import it into another module, like BookModule

import { Module } from "@nestjs/common";
import { LoggingModule } from "src/logging/logging.module";
import { BookController } from "./book.controller";
import { BooksService } from "./books.service";


@Module({
    controllers: [BookController],
    providers: [BooksService],
    imports: [LoggingModule]
})
export class BooksModule {

}

and inside my controller I can do:

@Controller('books')
export class BookController {

    constructor(private booksService: BooksService, private loggingService: LoggingService) {}

the question is: When I need to import the whole module instead of the single service (LogginService) in providers, like:

@Module({
    controllers: [BookController],
    providers: [BooksService,LoggingService],
})
export class BooksModule {

Upvotes: 9

Views: 5238

Answers (1)

Jay McDoniel
Jay McDoniel

Reputation: 70450

99% of the time, import the module. In Nest, if you import the module, you get the same instance of the already created class. If you add the provider to the providers array, you end up getting a new instance, which is not something many people usually want. So long as the module exports the provider, you'll re-use the created instance, which means less memory usage, and less leaks of the number of class instances, which means less time tracking down why this.someClass.field doesn't equal this.someClass.field

Upvotes: 24

Related Questions