UnityRef is currently in early development. Some features may be incomplete and/or not functioning.

UNITYREF

Your Pit Stop For Solving ANYTHING in Unity

architecture

[CompositionRoot] Master Manual DI for Scene & Runtime Performance

Solution

project architectureperformanceoptimization

Unity 2021.x - Unity 6.3.x

Published Wed, Mar 11

Issue

 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.

Explanation

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:

  1. Create a CompositionRoot with a DefaultExecutionOrder of -100 to ensure it initializes before other scripts.
  2. Define an interface-based system where components like your interactor script implement a common interface.
  3. Use a Factory pattern for runtime objects, where the CompositionRoot provides dependencies to the factory.
  4. Subscribe to SceneManager.sceneLoaded to manage dependency wiring during additive scene loading.

Additional Tips

  • Use FindObjectsSortMode.None when calling FindObjectsByType to 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.