1

I have a Monobehaviour object BaseUnit which can have some states, so I created states factory, like in the Zenject example projects, but my question is how to pass reference of this BaseUnit when I create this factory of states for this BaseUnit?

public class UnitStateFactory
{
readonly UnitMoveState.Factory _moveState;
readonly UnitActiveState.Factory _activeState;
readonly BaseUnit _unit;

public UnitStateFactory(
     UnitMoveState.Factory mS,
     UnitActiveState.Factory aS,
     BaseUnit unit

     )
{

    _moveState = mS;
    _activeState = aS;
    _unit = unit;
    }
}
Argus Kos
  • 175
  • 1
  • 12
  • Do you have multiple instances of BaseUnit? And how do you create them (do you use Zenject for creationg)? – vmchar Mar 28 '18 at 12:19
  • Yes I have multiple instances of BaseUnit. All of them are created manually in the editor with Zenject binding script attached to them. – Argus Kos Mar 28 '18 at 12:38
  • According to DI practices you'd better make each BaseUnit have it's own factory (or share instance), so you have to inject the factory to unit – vmchar Mar 28 '18 at 12:44
  • Yes i'm doing this, injecting state factory in the unit, but then at some point state needs to know position of the unit and I don't how to pass this information appropriately is using DI. – Argus Kos Mar 28 '18 at 12:53
  • If you have BaseUnit which has a factory as a dependancy and you want to pass BaseUnit to factory as dependancy - it's circular dependancy, which cannot be done in any DI container. it's a bad architecture approach. But you can do it if you add smth like Init method to factory and make unit pass it self in this Init method – vmchar Mar 28 '18 at 13:08
  • I will think some more how to avoid this, thank you for your help – Argus Kos Mar 28 '18 at 13:18
  • I agree that circular dependencies are a sign of a bad design, but you can do them in zenject. You just can't do them with constructor injection - you have to use property / field / method injection instead. In cases like this, where you have a set of classes that you want to work together, you might consider using a subcontainer. Then within each subcontainer there would be an instance of BaseUnit, and a state factory, etc. and they could all treat each other as if they were singletons without a problem. – Steve Vermeulen Apr 11 '18 at 12:08

0 Answers0