Consider a NestJS Shared Module that exports a service. What happens to the service instance when this Shared Module is imported into multiple feature modules?
import { Module } from '@nestjs/common'; import { SharedService } from './shared.service'; @Module({ providers: [SharedService], exports: [SharedService], }) export class SharedModule {} // FeatureModuleA and FeatureModuleB both import SharedModule
Think about how NestJS handles providers exported from a shared module.
Importing a non-global Shared Module into multiple feature modules shares the same instance of the providers because NestJS uses a single injector per application context.
Which of the following code snippets correctly defines a Shared Module that exports a service for reuse?
Remember that services must be listed as providers to be injectable.
Services must be declared in the providers array to be instantiated by NestJS. Exporting them makes them available to other modules.
Given a Shared Module imported into two different modules, why might you see multiple instances of a service instead of one?
import { Module } from '@nestjs/common'; import { SharedService } from './shared.service'; @Module({ providers: [SharedService], exports: [SharedService], }) export class SharedModule {} // AppModule imports SharedModule twice accidentally
Consider how NestJS handles module imports and singleton scope.
When a module is imported multiple times without being global, NestJS creates separate injector contexts, leading to multiple instances of providers.
Consider a SharedService with a counter property incremented by two different feature modules. What will be the final counter value after both modules increment it once?
import { Injectable } from '@nestjs/common'; @Injectable() export class SharedService { counter = 0; increment() { this.counter++; } } // Both FeatureModuleA and FeatureModuleB import SharedModule which exports SharedService // Each calls sharedService.increment() once
Think about whether the service instance is shared or duplicated.
Since the Shared Module is imported normally, the same instance of SharedService is shared across modules, so the counter increments twice.
Which approach correctly makes a Shared Module globally available so it does not need to be imported in every module?
Check NestJS documentation about global modules.
Using the @Global() decorator marks the module as global, so its exported providers are available everywhere without explicit imports.