DEV Community

Long Châu
Long Châu

Posted on

2

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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay