How do you use Zenject with nested prefabs?

Look, in my game I have multiple locations, they are stored as prefabs with component Location. I load a location like this handle = Addressables.InstantiateAsync(assetKey);
When the prefab is loaded I manually inject dependencies in the prefabs component (Location) like this sceneContext.Container.Inject(component);
In my location prefab I have other instances of other prefabs (like health bars, mini games etc ) which also have dependencies and these dependencies have to be injected when the main prefab has been instantiated.

How can I inject dependencies to nested prefabs?

Oooh, that does sound tricky in the general sense.

It is my humble opinion that using ZenJect with Unity scenes / prefabs / scriptableobjects is simply adding another extra layer of DI onto what is already DI.

Scenes, prefabs and scriptableobjects ARE the Unity DI and it works 100%.

There’s a huge discussion here:

https://discussions.unity.com/t/926144

Perhaps one of the ZenJect tankies over there has an answer?

Personally, this is the “inject” pattern I use the most in Unity:

Factory Pattern in lieu of AddComponent (for timing and dependency correctness):

https://gist.github.com/kurtdekker/5dbd1d30890c3905adddf4e7ba2b8580

1 Like