Morten Meilby
Morten Meilby

Reputation: 51

How to implement chained models with loopback 4 without getting a Circular dependency

When models have circular dependencies Loopback reports an error. I am looking for a way to solve the issue without changing the models.

If a model relates to itself the solution seems to be using Getter.fromValue(). However, when relations are circular through more models this solution seems not so usefull.

An example with three models A, B, and C. Let us assume that A references B, B references C, and C references A. Then the repositories would look like this when following the LB4 documentation:

Repository A:
constructor(
@repository(BRepo) private bGetter: Getter<BRepo>,
...

Repository B:
constructor(
@repository(CRepo) private cGetter: Getter<CRepo>,
...

Repository C:
constructor(
@repository(ARepo) private aGetter: Getter<ARepo>,
...

But this leads to a circular dependency failure. So the question is - how to fix this without changing the model dependencies.

Upvotes: 1

Views: 480

Answers (1)

Morten Meilby
Morten Meilby

Reputation: 51

The solution seems to be binding the repositories as Singletons

@bind({scope: BindingScope.SINGLETON})
export class Repository ...

Default binding is Transient which triggers the circular dependency check.

Upvotes: 4

Related Questions