2

I'm trying to use Zenject in Unity. I have an interface and several implementations of it.

I want to inject with ID but also that the implementation will have the tick interface since it's not a MonoBehaviour.

So I have an IAttacker interface and a MeleeAttackImpl implementation.

Container.Bind<IAttacker>().WithId(AttackerTypeEnum.MELEEE).To<MeleeAttackImpl>().AsTransient();

I want to add

Container.BindInterfacesTo<MeleeAttackImpl>().AsTransient();

But it creates 2 different objects instead of instances that have the Tick interface and bind them to IAttacker.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Itamar Kerbel
  • 2,508
  • 1
  • 22
  • 29

1 Answers1

0

If you want to bind an interface to a determined implementation, why do you use two bindings? If you want only one instance of the object I would try: Container.BindInterfacesAndSelfTo<MeleeAttackImpl>().AsSingle(); or: Container.Bind<IAttacker>().To<MeleeAttackImpl>().AsSingle();

As Single() In the case you need the same instance provided from the container along the app (like a singleton).

From the documentation: "AsTransient - Will not re-use the instance at all. Every time ContractType is requested, the DiContainer will execute the given construction method again."

Many times intance is created in the binding itself. So maybe from the two binding two instances are created, one from each binding.

In case you need to create instances dynamically with all their dependencies resolved, what you need a is Factory.

rustyBucketBay
  • 4,320
  • 3
  • 17
  • 47
  • 1
    What I want is not AsSingle. I do want Zenject to create a new instance for each IAttacker but I want this instance to have the Tick() interface – Itamar Kerbel Dec 09 '20 at 12:20
  • is ITickable implemented in your class? (`MeleeAttackImpl: ITickable`). You need to implement it in your class an bind in the container for the tick to take place – rustyBucketBay Dec 09 '20 at 12:35
  • I never used `ToTrasient` in case that is what is coausing your problem. [This](https://groups.google.com/g/zenject/c/wuHAkGOOe3o?pli=1) might be of help. – rustyBucketBay Dec 09 '20 at 12:38
  • 1
    yes it is implemented. But as I understand, implementing is not enough. You need to bind the interfaces too in the Installer – Itamar Kerbel Dec 09 '20 at 18:36
  • Yes, implement it, and bind it in the container `Container.Bind().To()`, or with `BindInterfacesAndSelfTo`. You got some tips in the link of the previous comment. Give them a try – rustyBucketBay Dec 09 '20 at 19:10