比方說,我有一個類取決於接口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
正是我所需要的。謝謝! – Martin