Method Injection
If you need to inject dependencies into a type but can't do so with constructors, consider using method injection instead. This is most useful for MonoBehaviour
s but can be done with any class, including test cases within the Unity Test Framework.
The [Inject]
-annotated method can have any name and any accessibility level.
Recommendation
Consider whether injection into MonoBehaviour
s is necessary.
In an ideal code base where presentation and domain logic are properly decoupled, MonoBehaviour
s would act as views that are only responsible for rendering (or other user-visible feedback).
Of course, views still need to be able to access the state of the thing they're displaying (i.e. the game world). But a view can depend on other objects without maintaining its own state. Depending on how your game state is represented, it might be enough to provide it to your views through event arguments or serializable fields rather than [Inject]
.
If you inject dependencies into MonoBehaviour
s, you must know when the [Inject]
-annotated method is called with respect to Unity's object lifecycle. If your Awake()
, Start()
, or OnEnable()
methods need any dependencies from VContainer, consider moving their logic into your injection method.