Jasurbek Nabijonov
Jasurbek Nabijonov

Reputation: 1745

Nestjs Circular dependency forwardRef() drawbacks

Official Circular dependency says:

A circular dependency occurs when two classes depend on each other. For example, class A needs class B, and class B also needs class A. Circular dependencies can arise in Nest between modules and between providers.

While circular dependencies should be avoided where possible, you can't always do so.

What are the reasons for not using forwardRef()?

Upvotes: 16

Views: 11617

Answers (2)

Depending on your domain, the relations between your modules would be "naturally" interdependent. Even it's true you can apply techniques to avoid that, the result sometimes is "not natural", at least for humans, and can become hardly understandable for the team, creating new issues later on the maintainance.

As a non-official alternative, I wrote a post about how to delay at maximum the resolution of the services injections (that's basically at runtime). I was hardly inspired on Java and Spring annotation @Autowired.

You can read the full post here: https://fjbarrena.dev/blog/autowired-annotation-in-nestjs

For sure this approach will have drawbacks as well, but yeah, at least for my domain works pretty well.

Hope you find it useful!

Upvotes: 2

Jay McDoniel
Jay McDoniel

Reputation: 70460

Circular dependencies usually mean you have tightly bound logic and possibly unstable architecture that will not allow you to scale. If you really don't want to care about that, you can just sprinkle in forwardRef wherever you want, constructors and services, but that could lead to some strange, hard to resolve errors, and is generally seen as a bad practice amongst the Nest community.

Upvotes: 32

Related Questions