DEV Community

Sergey Telpuk
Sergey Telpuk

Posted on

9 1

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 {
    say():void;
}

Create ContrivedService and implement IContrived interface:

class ContrivedService implements IContrived{
    say():void{}
}

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:

@Module({
    controllers: [],
    providers: [
        ContrivedServiceProvider,
    ],
    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 {
    constructor(
        @Inject('IContrived')
        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!

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (2)

Collapse
 
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?

Collapse
 
sergey_telpuk profile image
Sergey Telpuk

To be short, you work with interfaces.

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more