Circular dependencies

A circular dependency problem occurs, when two or more services depend on each other. By default, the dependency injector cannot resolve this issue, because the resolving would end up in an infinite loop, as the dependencies would keep requesting each other.

For most cases, it is recommended to avoid services referencing to each other.

The following code will throw a CircularDependencyException.

@Service
class ServiceA {
    @Inject
    ServiceB serviceB;
}

@Service
class ServiceB {
    @Inject
    ServiceA serviceA;
}

void init() {
    assertThrows(
        CircularDependencyException.class, 
        () -> Container.get(ServiceA.class)
    );
}

Last updated