'How to properly inject object-scene dependencies in unity with zenject

I have a scene object with a Fruit test script whose interfaces I want to add to dependencies. To do this, I use the standard Zenject Binding script. However, this doesn't work. Please tell me how can I solve the problem?

enter image description here enter image description here



Solution 1:[1]

You need to tell the container what to do with the depencencies. This is done with installers. There is a installing phase where you need to set the relation between the classes and the instances that need to be provided by the container. I recomend to read the documentation which is very good in this case.

For the case of monobehaviours you need to check the Scene bindings section in the documentation.

public class Foo : MonoBehaviour
{
}

public class GameInstaller : MonoInstaller
{
    public Foo foo;

    public override void InstallBindings()
    {
        Container.BindInstance(foo);
        Container.Bind<IInitializable>().To<GameRunner>().AsSingle();
    }
}

public class GameRunner : IInitializable
{
    readonly Foo _foo;

    public GameRunner(Foo foo)
    {
        _foo = foo;
    }

    public void Initialize()
    {
        ...
    }
}

For your specific case:

pubic class Fruit: Monobehaviour. IInitializable, ITickable { public void Initialize() {

}
public void Tick() {

}

}

public class GameInstaller : MonoInstaller { public Fruit fruit;

public override void InstallBindings()
{
    Container.BindInstance(fruit);
    Container.Bind<IInitializable>().To<Fruit>().AsSingle();
    Container.Bind<ITickable>().To<Fruit>().AsSingle();
}

}

Or you can also bind all the interfaces at once with:
Container.BindInterfacesTo<Fruit>().AsSingle();.

You need to add the GameInstaller in your SceneContext component for the installers to run along with the overriden InstallBindings() method.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rustyBucketBay