유니티를 위한 DI 프레임워크 VContainer, Container API

IObjectResolver를 통해 직접적으로 DI Container에 접근할 수 있습니다!

VContainer는 자동으로 IObjectResolver를 등록하고 필요한 곳 어디든지 Inject합니다!

그래서, 다른 dependency에서 얻는 것처럼 IObjectResolver을 얻을 수 있습니다!

 

class ClassA
{
    public ClassA(IObjectResolver container)
    {
        // Get (or create) whatever is registered as ServiceA.
        // This might be a subclass if you registered the
        // subclass as a ServiceA.
        var serviceA = container.Resolve<ServiceA>();

        // Inject all relevant dependencies into foo. Injecting
        // an object twice will overwrite any property or
        // field (or call the method) which is marked with [Inject].
        container.Inject(foo);

        // Inject dependencies into the MonoBehaviours of this
        // GameObject and its descendents, regardless of whether
        // the targeted GameObjects and MonoBehaviours are enabled.
        container.InjectGameObject(gameObject);

        // Instantiate a GameObject from a prefab and inject
        // its MonoBehaviours (and those of its descendents) with
        // dependencies. If you're creating GameObjects through
        // other means (e.g. procedurally or from Addressables)
        // then consider using InjectGameObject.
        var object1 = container.Instantiate(prefab);

        // There are also overloads that mimic Object.Instantiate.
        var object2 = container.Instantiate(prefab, parent);
        var object3 = container.Instantiate(prefab, position, rotation, parent);
    }
}

 

만약 정기적으로 특정한 패턴안에서 IObjectResolver.Inject 을 사용한다면, IObjectResolver.Inject을 위한 확장(extension) 메서드를 작성하는 것을 고려해야합니다.

사실은, 거의 모든 IObjectResolver API는 확장 메서드를 가지고 있습니다!