在 DLL 中,我们定义了两个类(“Class1”和“Class2”),它们继承自一个接口(“IInterface”)和一个基类(“BaseClass”)。
我们正在使用 Castle Windsor 的 Fluent Registration API ( http://using.castleproject.org/display/IoC/Fluent+Registration+API ) 自动将所有从“BaseClass”(在该 DLL 中)继承的类注册到它们各自的接口。
对于特定的个性化,我们(从今天开始)使用“castle.xml”文件,它覆盖(使用“组件”标签)接口和具体类(由 Fluent Registration Api 注册)之间的关联。我们在 WindsorContainer 的构造函数中加载该 xml 文件。
代码是这样的:
//container's initialization:
var resource = new FileResource("Castle.xml");
var interpreter = new XmlInterpreter(resource);
var container = new WindsorContainer(interpreter);
container.AddFacility<TypedFactoryFacility>();
//...
//automatic type registration:
container.Register(
AllTypes
.FromAssemblyContaining<BaseClass>()
.BasedOn<BaseClass>()
.WithService.Select(
(t1, t2) => t1.GetInterfaces()
.Except(new[] {typeof (IDisposable)})
.Union(new[] {t1}))
.Configure(a => a.Named(a.ServiceType.Name)
.LifeStyle.Transient)
.AllowMultipleMatches()
);
默认情况下,如果我们向 Castle 询问 IInterface 对象,我们会得到“Class1”;要获得“Class2”,我们必须在“Castle.xml”文件中指定它。
今天,我试图摆脱 Castle.xml,在 fluent 配置中指定“组件”指令(在“AllTypes”指令之前):
container.Register(
Component
.For<IInterface>()
.ImplementedBy<Class2>()
.LifeStyle.Transient);
...但我们仍然得到一个 Class1 对象,好像“AllTypes”流利指令覆盖了“组件”指令(这很奇怪,因为 xml 文件中的“组件”指令有效)。
我究竟做错了什么?
编辑:我通过键名访问组件,“.Named()”解决了这个问题(感谢 Krzysztof):
container.Register(
Component
.For<IInterface>()
.ImplementedBy<Class2>()
.Named(typeof(IInterface).Name)
.LifeStyle.Transient);