# Dependency Injection — NestJS: Scalable Node.js APIs बनाना

Source: https://www.skillbyai.com/hi/nestjs/nestjs-dependency-injection

> Nest का IoC container, constructor injection और provider scopes समझें ताकि services हाथ से instantiate न करनी पड़ें।

## Constructor से Inject करें

NestJS automatically constructor से services को instantiate और inject करता है। Manual `new` की ज़रूरत नहीं।

```typescript
@Injectable()
export class UsersService {
  // service logic
}

@Controller('users')
export class UsersController {
  constructor(private usersService: UsersService) {}

  @Get()
  findAll() {
    return this.usersService.findAll();
  }
}
```

## Lazy loading और scopes

Default में, services singletons होती हैं (ऐप के लिए एक instance)। आप `REQUEST` या `TRANSIENT` scopes भी उपयोग कर सकते हैं per-request या per-use instances के लिए।

## Constructor injection का उदाहरण

Nest constructor के parameter types पढ़कर matching provider दे देता है।

- `@Injectable()` class को provider बनाता है।
- `private readonly users: UsersService` dependency को declare और store दोनों करता है।
- आप खुद `new UsersService()` नहीं लिखते।

```ts
import { Controller, Get, Injectable } from '@nestjs/common';

@Injectable()
export class UsersService {
  findAll() {
    return ['asha', 'ravi'];
  }
}

@Controller('users')
export class UsersController {
  constructor(private readonly users: UsersService) {}

  @Get()
  list() {
    return this.users.findAll();
  }
}
```

## DI से tests आसान क्यों होते हैं

क्योंकि controller अपनी service खुद नहीं बनाता, उसे मिलती है, इसलिए test में fake service दी जा सकती है। controller को test करने के लिए database नहीं चाहिए।

त्वरित जाँच

**Quiz:** एक provider `providers` में है, पर दूसरे module में inject करने पर error आता है। क्या कमी है?

- [x] उसके module को उसे export करना होगा और उस module को import करना होगा
- [ ] class पर `@Controller()` चाहिए
- [ ] Nest सिर्फ़ `Service` नाम वाले providers inject करता है

*Answer:* उसके module को उसे export करना होगा और उस module को import करना होगा. providers अपने module में private रहते हैं जब तक export न हों, और consumer को वह module import करना पड़ता है।
