2

My setup is as below -

public class ParentModel {
    private StatusModel sm;
}

StatusModel class is as below -

public class StatusModel {
    private ParentModel pm;

    public void setParentModel(ParentModel pm) {
        this.pm = pm;
    }
}

pm inside StatusModel is the reference of ParentModel instance upon which the StatusModel depends.

Inside dao - I'm injecting ParentModel as below

@Inject
private Instance<ParentModel> factory;

but, setting ParentModel reference to StatusModel using a separate method call as below -

pm = factory.get();
pm.setters...
pm.getSm().setParentModel(pm);//<----- is it possible to avoid this?

Can we obtain the pm reference inside sm without a method call?

Tirath
  • 2,294
  • 18
  • 27
  • 1
    It’s a cyclic dependency, there’s no unambiguous way for a DI container to correctly determine the order in which to create the objects. Lateral suggestion: don’t; instead, extract the functionality that `StatusModel` needs into a new class you can inject into both it and `ParentModel`. – millimoose Nov 22 '17 at 10:42

1 Answers1

1

Depending on which object may be, however briefly, in an incompletely initialized state, inject that object into the other one as a constructor parameter, and call the setter there. The whole object hierarchy will then be consistent when you resolve the latter object:

class ParentModel {
    StatusModel _status;
    ParentModel(@Inject StatusModel status) {
        _status = status;
        _status.setParent(this);
    }
}

class StatusModel {
    ParentModel _parent;
    void setParent(ParentModel parent) { _parent = parent);
}

That said, I would suggest breaking this cyclic dependency up, because then you can restore a nice-to-have property of the design where it’s impossible to construct invalid objects.

millimoose
  • 39,073
  • 9
  • 82
  • 134