[更新]现在可以在Windsor 2.1或更新版本中使用.有关语法
here,请参阅文档.
原文链接:https://www.f2er.com/xml/293021.html此功能尚未在XML解释器中实现.但是通过工具添加对它的支持并不困难(显然,当想要添加现有配置解析器中不存在的其他功能时,此技术也很有用).
首先,我们添加一个工具,它将检测何时为类型创建处理程序,同时将注册任何转发的服务,以便它们指向现有的处理程序:
public class HandlerForwardingFacility : AbstractFacility { IConversionManager conversionManager; protected override void Init() { conversionManager = (IConversionManager)Kernel.GetSubSystem(SubSystemConstants.ConversionManagerKey); Kernel.HandlerRegistered += new HandlerDelegate(Kernel_HandlerRegistered); } void Kernel_HandlerRegistered(IHandler handler,ref bool stateChanged) { if (handler is ForwardingHandler) return; var model = handler.ComponentModel; if (model.Configuration == null) return; var forward = model.Configuration.Children["forward"]; if (forward == null) return; foreach (var service in forward.Children) { Type forwardedType = (Type)conversionManager.PerformConversion(service,typeof (Type)); Kernel.RegisterHandlerForwarding(forwardedType,model.Name); } } }
然后我们当然需要在代码中使用它,对于这个例子,我将有一个支持两个独立服务的变异鸭/狗组件 – IDuck和IDog:
public interface IDog { void Bark(); } public interface IDuck { void Quack(); } public class Mutant : IDog,IDuck { public void Bark() { Console.WriteLine("Bark"); } public void Quack() { Console.WriteLine("Quack"); } }
现在实际配置容器:
<castle> <facilities> <facility id="facility.handlerForwarding" type="Example.Facilities.HandlerForwardingFacility,Example" /> </facilities> <components> <component id="mutant" service="Example.IDog,Example" type="Example.Mutant,Example"> <forward> <service>Example.IDuck,Example</service> </forward> </component> </components> </castle>
现在我们可以愉快地执行这样的测试:
WindsorContainer container = new WindsorContainer(new XmlInterpreter()); var dog = container.Resolve<IDog>(); var duck = container.Resolve<IDuck>(); Assert.AreSame(dog,duck);
希望这可以帮助.