[Zenject] 종속성 매핑

Dev W·2022년 12월 14일
0

zenject

목록 보기
3/7

젠젝트의 Container는 객체를 생성하거나 포함하며,

바인딩 문을 사용하여 특정 인스턴스를 특정 타입에 매핑할 수 있다.

이렇게 타입을 인스턴스에 바인딩하는 것을 종속성 매핑(Dependency Mapping)이라 한다.

// 컨테이너에서 Player를 생성하고 Player 타입에 매핑한다.
Container.Bind<Player>().AsSingle();

public class Player
{
}

public class Monster
{
	private Player _player;
    
    // 몬스터 생성시 컨테이너에서 생성한 Player 인스턴스를 주입한다.
	public Monster(Player player)
    {
    	_player = player;
    }
}

식별값 (Identifiers)

바인딩시 아이디값을 지정하면 해당 바인딩을 고유하게 식별할 수 있다.

// 컨테이너에서 Pistol을 생성하고 IWeapon 타입에 매핑한다.
Container.Bind<IWeapon>().To<Pistol>().WithId("PlayerWeapon");

public class Player
{
	// "PlayerWeapon" 아이디값을 가진 IWeapon 객체를 주입한다.
	[Inject(Id = "PlayerWeapon")]
    private IWeapon _weapon;
    
    public Player (IWeapon weapon)
    {
    }
}

public class Pistol : IWeapon
{
}

이는 동일한 타입에 대해 여러개의 바인딩이 필요할때 유용하다.


구성 (Construction Method)

젠젝트는 여러 유형의 생성 방법을 지원한다.

// FromNew() : 컨테이너는 new T()로 인스턴스를 생성하여 타입에 매핑한다. (기본값)
Container.Bind<IWeapon>().To<Pistol>().FromNew();

// FromInstance() : 전달받은 인스턴스로 타입에 매핑한다.
Container.Bind<IWeapon>().To<Pistol>().FromInstance(new Pistol());

// FromFactory() : 팩토리의 Create()으로 생성한 인스턴스를 타입에 매핑한다.
Container.Bind<IWeapon>().To<Pistol>().FromFactory<PistolFactory>();

public class PistolFactory : IFactory<Pistol>
{
	public Pistol Create()
    {
    	return new Pistol();
    }
}

범위 (Scope)

주입되는 인스턴스의 재사용 여부를 결정한다.


// AsTransient() : 주입할때마다 인스턴스를 새로 생성한다. (기본값)
Container.Bind<IWeapon>().To<Pistol>().AsTransient();

// AsCached() : 처음 주입할때 인스턴스를 생성하고, 이후의 주입시에는 재사용한다.
Container.Bind<IWeapon>().To<Pistol>().AsCached();

// AsSingle() : AsCached()와 동일하지만 이미 생성된 인스턴스가 있으면 Exception을 발생시킨다.
Container.Bind<IWeapon>().AsSingle();

인수 (Arguments)

새 인스턴스를 생성할때 인수를 넘겨줄 수 있다.


// WithArguments() : 인스턴스 생성시에 값을 전달한다.
Container.Bind<IWeapon>().To<Pistol>().WithArguments(120);

public class Pistol
{
	public int BulletCount { get; private set; }
    
    public Pistol (int bulletCount)
    {
    	BulletCount = bulletCount;
    }
}

조건 (Conditions)

특정 조건이 충족될때에만 인스턴스를 주입할 수 있다.


// 주입을 요청한 객체의 타입이 Player일때에만 Pistol 인스턴스를 주입한다.
Container.Bind<IWeapon>().To<Pistol>().When(c => c.ObjectType == typeof(Player));

public class Player
{
	private IWeapon _weapon;
    
    // IWeapon에 Pistol 인스턴스가 주입된다.
    public Player (IWeapon weapon)
    {
    	_weapon = weapon;
    }
}

public class Enemy
{
	private IWeapon _weapon;
    
    // IWeapon에 인스턴스가 주입되지 않는다.
    public Enemy (IWeapon weapon)
    {
    	_weapon = weapon;
    }
}

Non Lazy

NonLazy를 사용하면 컨테이너 시작시 인스턴스를 바로 생성한다.
NonLazy를 사용하지 않으면 주입시 인스턴스를 생성한다.


// 컨테이너에 Player 인스턴스를 즉시 생성하여 매핑한다.
Container.Bind<Player>().AsSingle().NonLazy();

하위 컨테이너 (Sub Containers)

바인딩문을 모든 하위 컨테이너에 복사할 수 있다.


// 모든 하위 컨테이너에서도 Pistol을 생성하고, IWeapon 타입에 매핑한다.
Container.Bind<IWeapon>().To<Pistol>().CopyIntoAllSubContainers();

0개의 댓글