Search code examples
c#unity-game-enginedependency-injectionzenject

Multiple calls for method binding in Zenject


I have a MonoBehaviour that uses method injection :

    [Inject]
    private void Init(IFirst first, ISecond second)
    {
        _first = first;
        _second = second;
        StartService();
        Debug.LogError("Should only appear once!");
    }

For some reason this method is getting called twice by Zenject, and I dont understand why. Even worse: If I add a Update method to the class, which doesnt do anything special (and does NOT call Init!) suddenly Init gets called 7 times! The Update doesnt do anything fancy:

    private void Update()
    {
        //return;  <-- if this is added, init gets called 2 times by zenject, otherwise 7 times
        if (someFlag)
        {
            SomeGlobalField = "something"
            someflag = false;
        }
        if (!SomeGlobalField.Equals(SomeOtherGlobalField))
        {
            SomeOtherGlobalField = SomeGlobalField;
            StartService();
        }
    }

The only connection between both is that they both call StartService, which again isnt doing anything special, just calling a method on one of the injected fields.

Can someone enlighten me what might be going on here? I am using ProjectContext. I checked some other classes which seemed fine. The class is only added to one gameobject in the scene.


Solution

  • I missed the fact that the StartService method call could cause a scene switch quickly back and forth (immediately, so that I was not aware of it happening). So the inject method was called several times because I entered this scene several times. Maybe this helps someone else :)