我已经通过以下方式使用 Castle Windsor 注册了多个接口实例:
ServiceLocatorHelper.Register(
Component.For<ISerializerAdapter>()
.ImplementedBy<SerializerAdapter>(),
Component.For<IDriver>()
.ImplementedBy<FileDriver>()
.Named(SerializationType.Binary.ToString()),
Component.For<IDriver>()
.ImplementedBy<XmlDriver>()
.Named(SerializationType.Xml.ToString()),
Component.For<IBroker>().ImplementedBy<Broker>()
);
依赖关系如下:
+ IBroker
- IDriver
types
{
- FileDriver
- XmlDriver
}
- ISerializerAdapter
所以为了创建一个新对象,这是默认的构造函数顺序:
IBroker broker = new Broker(new IDriver(new ISerializerAdapter));
问题是: 当我通过以下方式使用城堡解决新的 IDriver 时:
IBroker broker = container.Resolve<IBroker>();
IDriver driver = broker.Driver;
Assert.IsTrue(driver.GetType() == typeof(FileDriver));
属性 IDriver 始终是FileDriver类型,而如果我使用密钥解析 IDriver 它会返回正确的类型:
IDriver fileDriver = container.Resolve<IDriver>(SerializationType.Binary.ToString());
Assert.IsTrue(fileDriver.GetType() == typeof(FileDriver));
IDriver fileDriver = container.Resolve<IDriver>(SerializationType.Xml.ToString());
Assert.IsTrue(fileDriver.GetType() == typeof(XmlDriver));
我怎么能说这样的话?
IBroker broker = container.Resolve<IBroker>("Xml");
Assert.IsTrue(broker.Driver.GetType() == typeof(XmlDriver));