ssannandeji / Zenject-2019

Dependency Injection Framework for Unity3D
MIT License
2.53k stars 363 forks source link

[Idea] Non-Generic BindInstance() #167

Open gregee123 opened 7 years ago

gregee123 commented 7 years ago

I came across a situation where I needed to install bindings to a few MonoBehaviours.

MBs need to be instantiated first, so they need to be dropped in the scene somewhere or wrapped in a prefab.

They way I wanted to go about it was to attach those MBs to the SceneContext GO and then add references to those instances to a public list exposed by my installer which would then iterate over that list and install bindings to their respective derived classes but without the ability to pass the derived type to BindInstance there's no simple way to do it. There are all kinds of workarounds, I can use prefabs/resources an such but this is unnecessarily labor-intensive.

Could you add such a method?

Even better if you could add something like BindMonoBehaviours(IList) and then call .GetType() on each of them internally that would save some coding in such circumstances.

Would that be worth considering?

svermeulen commented 7 years ago

Is this what you're trying to do?

foreach (var someMonoBehaviour in someMonoBehaviours)
{
    Container.Bind<IFoo>().To<SomeMonoBehaviour>().FromInstance(someMonoBehaviour);
}
gregee123 commented 7 years ago

I cannot pass SomeMonoBehaviour cause all those MBs have different derived classes and I need them to be bound to those derived classes not to some base class.

svermeulen commented 7 years ago

In that case, what about this?

Container.Bind<IFoo>().To(foo.GetType()).FromInstance(foo)

Or this:

Container.Bind(foo.GetType().GetInterfaces()).To(foo.GetType()).FromInstance(foo)
svermeulen commented 7 years ago

Actually this should work too. The To<> actually seems unnecessary

Container.Bind<IFoo>().FromInstance(foo)
Container.Bind(foo.GetType().GetInterfaces()).FromInstance(foo)
gregee123 commented 7 years ago

This actually does work. Still a non-generic BindInstance() would save some typing and the list<> based method would save the iteration. Please consider.

Thanks a lot for the tip. That would be it.

svermeulen commented 7 years ago

Yeah, a non-generic bind instance would be easy enough to add. I'll leave this item open so that we can add that