ZenAutoInjecter - mariaheine/Zenject-But-Wiki GitHub Wiki

As explained in the section on factories, any object that you create dynamically needs to be created through zenject in order for it to be injected. You cannot simply execute GameObject.Instantiate(prefab), or call new Foo().

However, this is sometimes problematic especially when using other third party libraries. For example, some networking libraries work by automatically instantiating prefabs to sync state across multiple clients. And it is still desirable in these cases to execute zenject injection.

So to solve these cases, we've added a helper MonoBehaviour that you can add to these kinds of objects called ZenAutoInjecter. If you add this MonoBehaviour to your prefab, then you should be able to call GameObject.Instantiate and injection should happen automatically.

After adding this component you might notice that there is a field on it called 'Container Source'. This value will determine how it calculates which container to use for the injection and has the following options:

  1. SearchInHiearchy - This will find the container to use by searching the scene hierarchy where the prefab is instantiated. So if the prefab is instantiated underneath a GameObjectContext, it will use the container associated with the GameObjectContext. If it is instantiated underneath a DontDestroyOnLoad object, then it will use the ProjectContext container. And otherwise will use the SceneContext container for whatever scene it is instantiated in.
  2. SceneContext - Don't bother searching the hierarchy and instead just always use the current SceneContext container.
  3. ProjectContext - Don't bother searching the hierarchy and instead just always use the ProjectContext container.