Skip to main content

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 MonoBehaviours but can be done with any class, including test cases within the Unity Test Framework.

public class SomeBehaviour : MonoBehaviour
float speed;
public void Construct(GameSettings settings)
speed = settings.speed;

The [Inject]-annotated method can have any name and any accessibility level.


Consider whether injection into MonoBehaviours is necessary.

In an ideal code base where presentation and domain logic are properly decoupled, MonoBehaviours 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 MonoBehaviours, 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.