Unity VContainer

VContainer #1 - 설치 및 실행

종잇장 2024. 8. 4. 12:01

 

VContainer 설치

 

Package Manager 좌측상단 [+] 버튼을 클릭해서 [Add package from git URL...] 메뉴를 클릭합니다.

 

https://github.com/hadashiA/VContainer.git?path=VContainer/Assets/VContainer

위 주소를 입력한 후 [Add] 버튼을 클릭하여 설치합니다.

 

Unity Package Manager에 대해 자세한 방법은 매뉴얼 확인해보시면 됩니다.

https://docs.unity3d.com/Manual/upm-ui.html

 

Unity - Manual: Package Manager window

Loading SSH keys automatically on macOS Access the Package Manager window Package Manager window Use the Package Manager window to: View which packages and feature sets are available for installation or already installed in your project. Check which packag

docs.unity3d.com

 

위 방법 이외에 다른 설치 방법은 VContainer 매뉴얼 확인해보시면 됩니다.

https://github.com/hadashiA/VContainer?tab=readme-ov-file#installation

 

GitHub - hadashiA/VContainer: The extra fast, minimum code size, GC-free DI (Dependency Injection) library running on Unity Game

The extra fast, minimum code size, GC-free DI (Dependency Injection) library running on Unity Game Engine. - hadashiA/VContainer

github.com

 

 

 

LifetimeScope 만들기

 

MonoBehaviour 스크립트 만들듯이 [C# Script]메뉴를 통해 생성합니다.

 

스크립트 네이밍을 ~~LifetimeScope로 설정해 줍니다.

 

using VContainer;
using VContainer.Unity;

public class HelloWorldLifetimeScope : LifetimeScope
{
    protected override void Configure(IContainerBuilder builder)
    {
    }
}

네이밍을 맞춰주면 자동으로 LifetimeScope 템플릿으로 스크립트가 만들어집니다.

 

Scene에 GameObject를 만들고 새로 생성한 스크립트를 추가해 줍니다.

 

 

Manager 만들고 등록하기

 

public class HelloWorldManager
{
    public void HelloWorld()
    {
        Debug.Log("Hello World!");
    }
}

간단하게 Manager 코드를 만들었습니다.

 

public class HelloWorldLifetimeScope : LifetimeScope
{
    protected override void Configure(IContainerBuilder builder)
    {
        builder.Register<HelloWorldManager>(Lifetime.Singleton);
    }
}

builder에 Register함수를 통해 HelloWorldManager를 등록해 줍니다.

이렇게 등록된 클래스는 이후에 의존성 주입이 되게 됐을 때 LifetimeScope에서 생성해서 주입해 주게 됩니다.

 

 

Presenter 만들고 등록하기

 

public class UIHelloWorldPresenter : MonoBehaviour
{
}

UI MVP모델로 Presenter를 구현한다고 가정하고 스크립트를 만들었습니다.

 

[VContainer.Inject] private HelloWorldManager m_HelloWorldMgr;

VContainer.Inject Attribute를 추가하여 이전에 만든 Manager 클래스를 멤버변수로 만들어줍니다.

LifetimeScope에서 Presenter를 등록해 주게 되면 Attribute 여부를 확인하여 등록된 클래스를 주입해 주게 됩니다.

 

private void Start()
{
    m_HelloWorldMgr.HelloWorld();
}

Start함수에서 HelloWorld함수를 실행해 줍니다.

LifetimeScope가 Awake함수에서 실행다보니 Awake함수에서는 주입되지 않았을 수 있어서 보통은 Start함수 나 Inject 함수를 만들어서 사용합니다.

 

UIHelloWorldPresenter 이름으로 GameObject를 만들고 스크립트를 추가해 줍니다.

 

HelloWorldLifetimeScope 컴포넌트 [Auto Inject Game Objects] 항목에 UIHelloWorldPresenter 오브젝트를 추가해 줍니다.

 

이 상태로 플레이모드로 전환하게 되면 정상적으로 실행되는 것을 볼 수 있습니다.