Register MonoBehaviour

Register from LifetimeScope's [SerializeField]#

[SerializeField]
YourBehaviour yourBehaviour;
// ...
builder.RegisterComponent(yourBehaviour);
note

RegisterComponent similar to RegisterInstance. The only difference is that MonoBehaviour registered with RegisterComponent will be injected even if not Resolved.

Register from scene with LifetimeScope#

builder.RegisterComponentInHierarchy<YourBehaviour>();
note

RegisterComponentInHierarchy always .Scoped lifetime. Because lifetime is equal to the scene.

Register component that Instantiate from prefab when resolving#

[SerializeField]
YourBehaviour prefab;
// ...
builder.RegisterComponentInNewPrefab(prefab, Lifetime.Scoped);

Register component that with new GameObject when resolving#

builder.RegisterComponentOnNewGameObject<YourBehaviour>(Lifetime.Scoped, "NewGameObjectName");

Register component as interface#

builder.RegisterComponentInHierarchy<YourBehaviour>()
.AsImplementedInterfaces();

Register component to specific parent Transform#

builder.RegisterComponentFromInNewPrefab<YourBehaviour>(Lifetime.Scoped)
.UnderTransform(parent);

Or find at runtime.

builder.RegisterComponentFromInNewPrefab<YourBehaviour>(Lifetime.Scoped)
.UnderTransform(() => {
// ...
return parent;
});

Grouping MonoBehaviour's Registration#

builder.UseComponents(components =>
{
components.AddInstance(yourBehaviour);
components.AddInHierarchy<YourBehaviour>();
components.AddFromNewPrefab(prefab, Lifetime.Scoped);
components.AddOnNewGameObject<YourBehaviour>(Lifetime.Scoped, "name");
})

This is the same as:

builder.RegisterComponent(yourBehaviour);
builder.RegisterComponentInHierarchy<YourBehaviour>();
builder.RegisterComponentFromNewPrefab(prefab, Lifetime.Scoped);
builder.RegisterComponentOnNewGameObject<YourBehaviour>(Lifetime.Scoped, "name");

Execute only Inject for MonoBehaviour on the scene#

In VContainer, objects that are not explicitly registered will not be injected. Therefore, execute Register for the object you want to inject.

If you want to run "Inject Only" into MonoBehaviour, you can do so by inserting GameObject in the autoInjectGameObject field of LifetimeScope.