2014-10-22 71 views
2

我想註冊服務IInterface<T>,使得如果在某個程序集中存在實現IInterface<T>的類,則使用該類,但如果該類不存在,則使用Fallback<T>註冊通用接口與回退

例如,假設我已經定義了一個類CatImplementer : IInterface<Cat>

如果我問容器爲IInterface<Cat>我會得到CatImplementer。但如果我要求IInterface<Dog>,我會得到Fallback<Dog>,因爲我還沒有創建一個實現IInterface<Dog>的類。

可以這樣做嗎?

回答

4

鑑於你的榜樣,你不需要做什麼特別的事情不管你是明確註冊類型:

container.Register(Component.For(typeof(IInterface<Cat>)).ImplementedBy(typeof(CatImplementer))); 
container.Register(Component.For(typeof(IInterface<>)).ImplementedBy(typeof(Fallback<>))); 

或含蓄:

​​

在這兩種情況下,下面的代碼:

IInterface<Cat> cat = container.Resolve<IInterface<Cat>>(); 
IInterface<Dog> dog = container.Resolve<IInterface<Dog>>(); 

Console.WriteLine("cat.GetType() -> " + cat.GetType()); 
Console.WriteLine("dog.GetType() -> " + dog.GetType()); 

當使用這些對象時:

public interface IInterface<T> { } 

public class CatImplementer : IInterface<Cat> { } 

public class Fallback<T> : IInterface<T> { } 

public class Cat { } 

public class Dog { } 

會打印:

cat.GetType() -> ConsoleApplication1.CatImplementer 
dog.GetType() -> ConsoleApplication1.Fallback`1[ConsoleApplication4.Dog] 

如果不爲你在你的實際使用情況(使用城堡3.3)工作,則必須有一個關鍵部分,這是不同的。隨意添加到您的問題,如果是這樣的話。

+0

令人驚歎........ – David 2014-10-23 08:08:06

相關問題