Injecting into MonoBehaviours
As MonoBehaviour
s do not support constructors, you must use method injection to inject them with dependencies.
Note that the presence of the [Inject]
attribute on a MonoBehaviour
's method does not imply that it will automatically be called. You must inject dependencies manually in one of the following three ways:
- If you want to inject into a specific
MonoBehaviour
, you can specify it in theLifetimeScope
's inspector.- The
MonoBehaviour
s of all specifiedGameObject
(and their children) will be automaticallyInject
ed when theLifetimeScope
is initialized.
- The
- Use one of the
RegisterComponent*
methods to register theMonoBehaviour
instance to the container.- In this case, the registered
MonoBehaviour
will bothInject
and beInject
ed into other classes. - See Register MonoBehaviour
- In this case, the registered
- To inject into dynamically-generated
MonoBehaviour
s at runtime (e.g. from prefabs), useIObjectResolver.Instantiate
instead ofUnityEngine.Object.Instantiate
. (Factory patterns and object generation expressions can be registered.)
MonoBehaviour
s?#
Why doesn't VContainer automatically inject into all - Unity doesn't provide a good way to listen for the creation of all
GameObject
s orMonoBehaviour
s. Rather than having some cases that are automaticallyInject
ed and some that are not, we decided on explicitInject
ion that you can use to fit your own needs. - We do not recommend excecuting
Inject
directly onMonoBehaviour
s; instead, useInjectGameObject
on the owningGameObject
.- This is because the purpose of VContainer and DI is inversion of control of MonoBehaviour.
- If a
MonoBehaviour
needs an explicitInject
call, you risk losing the advantages of Unity's prefab portability.