---
# System prepended metadata

title: NestJS DI
tags: [learning]

---

# NestJS DI

###### tags: `learning`

### What is DI, IoC, IoC container anyway?

### NestJS module revisited
![](https://docs.nestjs.com/assets/Modules_1.png)
- Root module
- Feature module
- Global module
- Module import tree 
    - Handon
    
Refs: 
https://docs.nestjs.com/modules

### NestJS provider revisited
![](https://docs.nestjs.com/assets/Components_1.png)
- Services, repositories, helpers...
- Injectable
- DI
    - Contructor-based
    - Property-based
    - What if we don't have access to DI for a particular provider?
        - In `bootstrap()` method
- Injection scopes
    - Default
    - Hierarchy
    - Handon
- Class-based vs non-class-based & short-hand
- Custom provider with compatible interface (structural typing)
- IoC container and DI flow
```plantuml
@startuml
(*) --> Factory create (NestFactory)
--> Create IoC container (NestContainer)
--> Scan and register dependencies meta (providers, controllers...) to IoC container (DependenciesScanner)
--> Instantiate dependencies (DI) (InstanceLoader & Injector)
--> Application initialization (NestApplication)
@enduml
```

Refs:
https://docs.nestjs.com/providers
https://docs.nestjs.com/fundamentals/custom-providers
https://github.com/nestjs/nest/blob/master/packages/core/nest-factory.ts

### Common issues
#### Circular dependency
- Forward ref (provider vs module)
- Barrel file
#### Cannot resolve dependencies
https://docs.nestjs.com/faq/common-errors

        - 