Member-only story

Dependency Injection Scopes In NestJS

İbrahim Gündüz
2 min readMar 25, 2023

--

NestJS is one of the best server-side framework alternatives with the features it presents. Today we’re going to mention some secret power of the IoC container that comes out of the box with NestJS.

Normally, the framework manages providers` lifetime as singleton. In other words, having stateful objects in the container may create some issues. Let’s take a look at the following example:

// src/http-client.ts
import { Injectable } from "@nestjs/common";

@Injectable()
export class HttpClient {
//...
public setDefaultBaseUrl(baseUrl: string): void {
this.baseUrl = baseUrl;
}
//...
}

// src/payment-service.ts
//...

@Injectable()
export class PaymentService {
public constructor(
private readonly client: HttpClient,
@Inject('payment-service.url') private readonly serviceUrl: string,
) {
this.client.setDefaultBaseUrl(serviceUrl);
}
//...
}

// src/delivery-service.ts
//...

@Injectable()
export class DeliveryService {
public constructor(
private readonly client: HttpClient,
@Inject('delivery-service.url') private readonly serviceUrl: string,
) {
this.client.setDefaultBaseUrl(serviceUrl);
}
//...
}

So, if you have such a class like HttpClient above, once setDefaultBaseUrl() method is called, it would change whole other services` behavior dependent on itself.

--

--

No responses yet