2008-12-07 79 views
0

我遇到了使用Unity應用程序塊的問題,我創建了一個名爲Composition的基類。Unity應用程序塊,繼承注入

每個組合包含一個IUnityContainer,當我創建頂級對象UniversalComposition時,我想用UnityContainer初始化它。

從UniversalComposition創建的任何對象我想使用IUnityContainer.CreateChildContainer方法將一個子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 { } 

回答

1

我不認爲這將通過注入工作,因爲你有它在父級實現,因爲父容器不存在,直到子對象被實例化。因此您無法生成要注入的子容器。更好的方法是通過基類上的參數化構造函數注入父容器,然後將這兩個注入到子類中。默認的構造函數可以使用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(); 
    } 

} 
+0

謝謝,我怎麼能自動注入父和孩子到DerivedClass?我不能簡單地將它標記爲'[InjectionConstructor]' – 2008-12-07 23:03:34