0

有接口...在Castle Windsor中,如何注册泛型接口的许多实现中的一个实现泛型类型的实现?

IThing 
IWrapping<IThing> 

...通过Things实现...

Cookie : IThing 
Carmel : IThing 
Chocolate : IThing 

...和Wrappings他们...

Paper <TThing> : IWrapping<TThing> where TThing is IThing 
Foil <TThing> : IWrapping<TThing> where TThing is IThing 

...我选择一个实现Wrapping来运行该应用程序,忽略其他。要注册选择了所有已知的IThing实现我现在必须列出所有这些Wrapping

Component.For<IWrapping<Cookie>>() .ImplementedBy<Paper<Cookie>>(), 
Component.For<IWrapping<Carmel>>() .ImplementedBy<Paper<Carmel>>(), 
Component.For<IWrapping<Chocolate>>().ImplementedBy<Paper<Chocolate>>(), 

怎样一个寄存器所有的人都在一次?

Component.For<IWrapping<IThing>>() 
    .ImplementedBy<Paper<ALL_FOUND_IMPLEMENTATIONS_OF_ITHING>>(), // One place to switch between Paper and Foil 

回答

0

因为您正在处理Castle内的泛型类型参数,所以不能像使用它一样使用流畅的语法。

你可以做的是下面的一行:

container.Register(Component.For(typeof(IWrapping<>)).ImplementedBy(typeof(Paper<>))); 
var cookieWrapper = container.Resolve<IWrapping<Cookie>>(); 

在解决的依赖,你会得到以下结果:

Screenshot of the result upon resolving the wrapper

这是基于以下对象依赖关系设置(我反映了你在帖子中的内容,但只是想确保你能够完整地了解我所做的重现此操作的全貌):

public interface IThing {} 
public interface IWrapping<IThing> {} 
public class Paper<TThing> : IWrapping<TThing> where TThing : IThing {} 
public class Cookie : IThing {} 
public class Carmel : IThing{} 
public class Chocolate : IThing{}