DEV Community

Long Châu
Long Châu

Posted on

Dependency Injection with VContainer.

Github: https://github.com/LongChau/Test_CSV_Baking/tree/main
Reference link: https://vcontainer.hadashikick.jp/getting-started/hello-world
Link Zenjec: Zenject

We will split dependencies into 2 parts:
Project scope dependencies.
Scene scope dependencies.

Project scope dependencies:
Contains many "managers" that we mark them as DontDestroyOnLoad.
Work as "managers"
Can inject anywhere some object needs it.
Is a singleton.

Scene scope dependencies:
Objects in Hierachy that need to reference to others.
Lifetime equals to scene. Destroy scene => destroy this object.
Is not singleton.
Can be multiple objects. Instantiated by prefab.

To create project scope dependencies:
Create-> VContainer -> VContainer Setting

It will look like this. Then assign a prefab ProjectScope which has ProjectScope script inside it.

Project scope prefab:

Code:

using VContainer;
using VContainer.Unity;

namespace Test_CSV
{
    public class GameLifetimeScope : LifetimeScope
    {
        protected override void Configure(IContainerBuilder builder)
        {
            builder.Register<UserData>(Lifetime.Singleton);
            builder.RegisterComponentOnNewGameObject<GameManager>(Lifetime.Singleton, "GameManager").DontDestroyOnLoad();
            // builder.RegisterComponentInHierarchy<ViewController>();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Note: VContainer automatically assign this root scriptableobject to preloaded assets for us. But if you have issue about the injection, you should check it as well.

To create scene scope dependencies:
Parented it the project scope.

Code:

using VContainer;
using VContainer.Unity;

namespace Test_CSV
{
    public class SceneLifetimeScope : LifetimeScope
    {
        protected override void Configure(IContainerBuilder builder)
        {
            builder.RegisterComponentInHierarchy<ViewController>();

        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)