Using Zenject to inject an implementation with interfaces

Viewed 3307

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.

1 Answers

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.

Related