#Circular Dependency with Request Scoped Providers

6 messages · Page 1 of 1 (latest)

sage wraith
#

Assume that I have 2 request scoped services: UsersService and CommentsService on a social app platform and these services depend on each other causing a circular dependency. Let's also assume refactoring the code to break the circular dependency will make the code far more complex.

There are a couple of possible solutions that come to my mind:

  1. Use forwardRef which I don't think is the best way as it may result in undefined dependencies with request scoped providers
  2. Inject both usersRepository and commentsRepository in both services so there wont be any need for injecting the other service's instance as a dependency. That would break the circular dependency but would also violate single responsibility principle
  3. Create an intermediary service that injects both repositories and only expose common methods between two of these services. That way, both UsersService and CommentsService would inject that intermediary service, resolving circular dependency. However this doesn't really feel like the right way to do it

I would like to get your valuable opinion on this matter and would totally appreciate it if you could tell me in case there's another better way that I don't know. Thanks in advance.

sage wraith
#

Any idea?

remote swift
#

For 1. you alsio have to use a process.nextTick() for the circular deps to be defined during the runtime. I'll have to find that issue again where Kamil explains it

For 2. I would rather keep repos to the respective features, so I'd advocatye against it

For 3. I actually advocate for 3 when possible. It's coupled logic so actually make the coupled class, y'know?

sage wraith
#

Thanks for your insights @remote swift

sage wraith
#

I also found event driven approach where I dont even have to inject dependencies at all. Does anyone here think it's worth using?

remote swift
#

That's another option for dealing with circular deps