在 Castle Windsor 中,如何为所有找到的通用类型的实现注册通用接口的许多实现之一?
In Castle Windsor, how to register ONE of many implementations of generic interface for ALL found implementations of generic type?
有接口...
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
的所有已知实现注册 chosen 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
因为您在 Castle 中处理泛型类型参数,所以您不能完全按照您一直使用的方式使用流畅的语法。
你可以做的是下面一行:
container.Register(Component.For(typeof(IWrapping<>)).ImplementedBy(typeof(Paper<>)));
var cookieWrapper = container.Resolve<IWrapping<Cookie>>();
解决依赖关系后,您将得到以下结果:
这是基于以下对象依赖性设置(我反映了您在 post 中输入的内容,但只是想确保您全面了解我为重现此内容所做的工作):
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{}
有接口...
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
的所有已知实现注册 chosen 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
因为您在 Castle 中处理泛型类型参数,所以您不能完全按照您一直使用的方式使用流畅的语法。
你可以做的是下面一行:
container.Register(Component.For(typeof(IWrapping<>)).ImplementedBy(typeof(Paper<>)));
var cookieWrapper = container.Resolve<IWrapping<Cookie>>();
解决依赖关系后,您将得到以下结果:
这是基于以下对象依赖性设置(我反映了您在 post 中输入的内容,但只是想确保您全面了解我为重现此内容所做的工作):
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{}