2016-01-13 49 views
1

比方說,我有一個類取決於接口IFace以及注入構造函數的其他幾個依賴項(由...描述)。我也有2個實現的接口IFace在UnityContainer中註冊類型以使用其他命名註冊來解析構造函數參數

class Impl1 : IFace {} 
class Impl2 : IFace {} 

class Std : IStd { 
    Std(IFace impl1, IOtherDependency otherDep, ...) { ... } 
} 

我要註冊Impl1作爲默認的實現和註冊Impl2爲名爲執行其應注入某些類。

container.RegisterType<IFace, Impl1>(); 
container.RegisterType<IFace, Impl2>("impl2"); 

註冊Std這樣會注入默認Impl1實現:

container.RegisterType<IStd, Std>(); // this would inject the default implementation Impl1 

如何註冊Std有一個名爲注射執行不訴諸手動調用Resolve()?我能想出的最好的是這樣的:

container.RegisterType<IStd, Std>(
    new InjectionConstructor(new ResolvedParameter<IFace>("impl2"), typeof(IOtherDependency, ...))); 

我不與上面的方法一樣的是,我還需要指定其他所有構造函數的參數;當簽名發生變化時,我需要調整註冊,編譯器不會提出問題(運行時異常被拋出),而智能感知在此處不起作用。

我想吃點什麼是沿着線的東西:(該InjectNamedType顯然是由)

container.RegisterType<IStd, Std>(
    InjectNamedType<IFace>(name: "impl2")); // this would tell Unity to look for registration of IFace with that name 

回答

1

這裏是你如何能做到這一點:

container.RegisterType<IStd>(
    new InjectionFactory(x => 
     x.Resolve<Std>(new DependencyOverride<IFace>(x.Resolve<IFace>("impl2"))))); 

InjectionFactory讓你指定創建IStd對象的工廠邏輯。我們使用Resolve方法來解析具體的Std類,我們使用DependencyOverride類來指定要使用哪個實現IFace。我們再次使用Resolve方法來解決特定的實現。

請注意,只有當有人試圖解決IStd(或類別取決於IStd)而不是當您註冊IStd時,工廠邏輯纔會運行。

+0

正是我所需要的。謝謝! – Martin

相關問題