Search code examples
node.jsapidependency-injectionnestjs

A Right Way To Inject Services


I have a complex application where services are injected into each other. What is your way of injecting service into each other. Like I have 5 services and need to inject them into each other. I'm injeccting a service everytime into other service. E.g. service_1, service_2, service_3, service_4 -> service_5 service_5, service_2, service_3, service_4 -> service_1 service_1, service_3, service_4, service_5 -> service_2

and so on. I inject all the services that are used inside that one.

I tried to creat application on described way but was creating problem. So need an architectural solution for this.


Solution

  • It is generally considered poor practice to have cyclic dependencies between modules. Dependency graphs should be Acyclic.

    That being said, in larger existing applications this is not an easily solvable problem. However, Nests does come with some facilities for dealing with circular dependencies.

    @Module({
        imports: [forwardRef(() => ModuleB)]
        //exports, controllers etc
    })
    export class Module A {}
    
    @Module({
        imports: [forwardRef(() => ModuleA)]
        //exports, controllers etc
    })
    export class Module B {}
    

    Something like the above would likely work for your use-case, tho, obviously the number of imports and their interconnection would change.

    If you would like to know more about how to design around needing cyclic dependencies and what their dangers are in larger products, I recommend looking into SOLID Design Principles, Clean Architecture and its cousins.