Nestjs & Inversion Of Control(IoC)

sergey_telpuk profile image Sergey Telpuk ・1 min read

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!

Posted on by:

sergey_telpuk profile

Sergey Telpuk


Experienced PHP/NodeJS/Golang Developer with a demonstrated history of working in the information technology and services industry.


markdown guide