Skip to content

Commit 467c189

Browse files
docs(modules): explain why shared module #2133
1 parent a0db24c commit 467c189

File tree

1 file changed

+4
-0
lines changed

1 file changed

+4
-0
lines changed

content/modules.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,10 @@ export class CatsModule {}
9999

100100
Now any module that imports the `CatsModule` has access to the `CatsService` and will share the same instance with all other modules that import it as well.
101101

102+
If we were to directly register the `CatsService` in every module that requires it, it would indeed work, but it would result in each module getting its own separate instance of the `CatsService`. This can lead to increased memory usage since multiple instances of the same service are created, and it could also cause unexpected behavior, such as state inconsistency if the service maintains any internal state.
103+
104+
By encapsulating the `CatsService` inside a module, such as the `CatsModule`, and exporting it, we ensure that the same instance of `CatsService` is reused across all modules that import `CatsModule`. This not only reduces memory consumption but also leads to more predictable behavior, as all modules share the same instance, making it easier to manage shared states or resources. This is one of the key benefits of modularity and dependency injection in frameworks like NestJS—allowing services to be efficiently shared throughout the application.
105+
102106
<app-banner-devtools></app-banner-devtools>
103107

104108
#### Module re-exporting

0 commit comments

Comments
 (0)