문제

Unity Application Block을 사용하는 데 문제가 있으며 Composition이라는 기본 클래스를 만들었습니다.

각 구성에는 iunityContainer가 포함되어 있으며, 최상위 객체 범용 회사를 만들 때 UnityContainer로 초기화하려고합니다.

UniversalComposition에서 생성되는 모든 객체는 iunityContainer.createChildContainer 메소드를 사용하여 child iunityContainer를 주입하고 싶습니다.

class Program
{
    static void Main(string[] args)
    {
        UniversalComposition universe = new UniversalComposition();


    }
}

public class UniversalComposition : Composition
{
    // Everything that gets resolved in this container should contain a child container created by the this container

    public UniversalComposition()
    {
        this.Container.RegisterType<IService, Service>();
    }

    protected override IUnityContainer CreateContainer()
    {
        return new UnityContainer();
    }

}

public abstract class Composition
{
    protected IUnityContainer Container {get; private set;}

    public Composition()
    {
        this.Container = this.CreateContainer();
    }

    public TInstance Resolve<TInstance>()
    {
        return this.Container.Resolve<TInstance>();
    }

    protected abstract IUnityContainer CreateContainer();
}

public class Service : Composition, IService
{
    public Service(/* I want to inject a child Unity Container in here container.CreateChildContainer() */)
    {
    }
}

public interface IService { }
도움이 되었습니까?

해결책

아동 객체가 인스턴스화 될 때까지 부모 컨테이너가 존재하지 않기 때문에 부모에게 구현 된대로 주사를 통해 이것이 작동하지 않을 것이라고 생각합니다. 따라서 주사 할 어린이 용기를 생성 할 방법이 없습니다. 더 좋은 방법은 기본 클래스의 매개 변수화 된 생성자를 통해 모 컨테이너를 주입 한 다음 아동 클래스에 둘 다 주입하는 것입니다. 기본 생성자는 NULL로 매개 변수화 된 생성자를 호출 할 수 있으며 매개 변수화 된 생성자는이를 감지하고 컨테이너가 지정되지 않은 경우 컨테이너를 만들 수 있습니다. 아래의 예는 명확성을 위해 단순화됩니다.

public abstract class BaseClass
{
    public IUnityContainer Container { get; protected set; }

    public BaseClass() : BaseClass(null) {}

    public BaseClass( IUnityContainer container )
    {
        this.container = container ?? this.CreateContainer();
    }

    public abstract IUnityContainer CreateContainer();
}

public class DerivedClass : BaseClass
{
    public IUnityContainer ChildContainer { get; private set; }

    public DerivedClass() : DerivedClass(null,null) {}

    public DerivedClass( IUnityContainer parent, IUnityContainer child )
        : BaseClass( parent )
    {
        this.ChildContainer = child ?? this.CreateChildContainer();
    }

    public IUnityContainer CreateContainer()
    {
         return new UnityContainer();
    }

    public IUnityContainer CreateChildContainer()
    {
         return this.Container.CreateChildContainer();
    }

}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top