代码之家  ›  专栏  ›  技术社区  ›  Rohan West

Unity应用程序块,继承注入

  •  0
  • Rohan West  · 技术社区  · 16 年前

    每个合成都包含一个IUnityContainer,当我创建顶级对象UniversalComposition时,我想用一个UnityContainer初始化它。

    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 { }
    
    1 回复  |  直到 9 年前
        1
  •  1
  •   tvanfosson    16 年前

    我认为这不会通过注入工作,因为您在父对象中实现了它,因为父容器在子对象实例化之前不存在。因此,您无法生成要注入的子容器。更好的方法是通过基类上的参数化构造函数注入父容器,然后将两者都注入子类。默认构造函数可以使用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();
        }
    
    }