[CompositionRoot] Master Manual DI for Scene & Runtime Performance
Solution
Unity 2021.x - Unity 6.3.x
Published Wed, Mar 11
The manual dependency injection setup utilizing a CompositionRoot to find all components via FindObjectsByType on every scene load poses scalability concerns for larger projects. Furthermore, objects instantiated at runtime do not automatically receive dependencies, necessitating a structured approach to ensure proper CompositionRoot wiring without performance bottlenecks.
The initial approach for manual Dependency Injection (DI) involves using FindObjectsByType<MonoBehaviour>() on every scene load to inject dependencies into interactable objects. This method presents scalability concerns due to potential performance bottlenecks in larger scenes. Furthermore, dynamically instantiated MonoBehaviour objects at runtime do not automatically receive dependencies, necessitating an additional mechanism to ensure proper wiring.
To optimize your architecture:
- Create a CompositionRoot with a
DefaultExecutionOrderof -100 to ensure it initializes before other scripts. - Define an interface-based system where components like your interactor script implement a common interface.
- Use a Factory pattern for runtime objects, where the CompositionRoot provides dependencies to the factory.
- Subscribe to
SceneManager.sceneLoadedto manage dependency wiring during additive scene loading.
Additional Tips
- Use
FindObjectsSortMode.Nonewhen callingFindObjectsByTypeto avoid unnecessary sorting overhead. - Transition from scene scanning to explicit registration for high-performance requirements.
- Implement a global CompositionRoot for persistent services and local roots for scene-specific logic.
TL;DR
Optimize manual dependency injection in Unity by using scene-specific CompositionRoot instances, factory patterns for runtime objects, and efficient discovery methods.
Related Posts Haven't quite found a solution to your problem? We think these posts might help you.
Content inspired by a Unity discussion post.