Zenject icon indicating copy to clipboard operation
Zenject copied to clipboard

i need to run GameObject Installer on an instantiated object

Open virtouso opened this issue 5 years ago • 3 comments

as i found out, public override void InstallBindings() only starts on start of the scene. even if its on a gameObject Context.

i need it wo run on object when instantiated but it doesnt.

virtouso avatar Nov 26 '20 13:11 virtouso

Hello there,

to be honest, I'm just another developer who used Extenject before, so I can't guarantee to have all the knowledge one could have regarding Extenject, so I might overlook the best solution as well.

As far as I understand it, you're not supposed to do a second installation process within the same context, since changing the list of injectable objects would require zenject to keep track of all objects that might be interested in getting more injection done to them. This fails as soon as an object only has constructor injection, or when you consider that zenject can't know when to drop references to instances.

After looking at the API a bit, the closest one I found you could get is creating a subcontext for instance you're trying to create and thus its installer. (I've used something like this before, but I'd have to read that code again.) If I'm not mistaken, this also requires that you're not just calling a random Instantiate somewhere in your code, but that you're using Extenject to create the prefab instances along with the subcontainer. The example project SampleGame2 (Advanced) in OptionalExtras contains code that creates new enemy ships using a factory, just look into the GameInstaller and notice the FromSubContainerResolve call.

I hope this helps in your situation.

In order for me (or someone else) to give some better help, it would be good to know what you're trying to achieve with the Installer on the Prefab. Maybe there is a better approach to your overall problem, so you don't have to have an installer on the Prefab.

Good luck with your game development anyway. ;)

RichardWepner avatar Dec 28 '20 04:12 RichardWepner

That's a great explanation Richard but doesn't it make it sort of useless as a DI framework then?

eviathan avatar Feb 06 '21 16:02 eviathan

That's a great explanation Richard but doesn't it make it sort of useless as a DI framework then?

It's bad practice in any DI framework to add to the container after you've already started resolving instances from it. This isn't particular to zenject. So if you want to run an installer for a dynamically created object that is not part of the initial object graph created at startup, then you will need to use a new context with a new sub-container. See the documentation around GameObjectContext for more detail

svermeulen avatar Feb 06 '21 16:02 svermeulen