DEV Community

Sergey Telpuk
Sergey Telpuk

Posted on

Nestjs & Inversion Of Control(IoC)

Hello friends!
I would like to talk about Nestjs and IoC. First of all I want to point out that I'm not expert of JavaScript world, but I seek for adapting best practice of coding to my js-projects.
Nestjs has a great documentation. I got acquainted with it and I saw lots of benefits of using that one. Installing skeleton is easy. I don't want to waste time on showing it.
Let's get down to describing how to use IoC.
Create a contrived interface:

interface IContrived {

Create ContrivedService and implement IContrived interface:

class ContrivedService implements IContrived{

After that to add the service provider for that interface:

const ContrivedServiceProvider: Provider = {
    provide: 'IContrived',//it's an injectable interface 
    useClass: ContrivedService,

Add ContrivedServiceProvider into ContrivedModule:

    controllers: [],
    providers: [
    imports: [],
export class ContrivedModule {}

It's suffice for using IoC with the help of interface. Last step is to inject our interface.
Inject ContrivedService into ContrivedController for instance:

export class ContrivedController {
        private readonly contrivedService: IContrived
    ) {}

This is a simple implementation of IoC and the first step towards achieving fully loose coupled design.
If you have any questions feel free to get in touch with me.

Best regards!

Top comments (2)

umairjyatoo profile image
Umair Yatoo

I am new to NestJs. Could you explain me about IoC in very easy words. Like, what it does and how useful it is?

sergey_telpuk profile image
Sergey Telpuk

To be short, you work with interfaces.