1

我已经通过以下方式使用 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));
4

1 回答 1

2

这是使用Typed Factory Facility的典型场景。

只需声明工厂接口:

public interface IBrokerFactory {
    IBroker GetXmlBroker();
    IBroker GetBinaryBroker();
}

并像这样注册它:

Component.For<IBrokerFactory>().AsFactory(),
Component.For<IBroker>().
          ImplementedBy<Broker>().
          Named("BinaryBroker").
          DependsOn(Dependency.OnComponent("BinaryDriver")),
Component.For<IBroker>().
          ImplementedBy<Broker>().
          Named("XmlBroker").
          DependsOn(Dependency.OnComponent("XmlDriver")),
Component.For<IDriver>().ImplementedBy<FileDriver>().Named("BinaryDriver"),
Component.For<IDriver>().ImplementedBy<XmlDriver>().Named("XmlDriver"),

GetXxx()方法名称应与 匹配,仅此.Named("Xxx")而已。用法:

var factory = container.Resolve<IBrokerFactory>();
IBroker broker = factory.GetXmlBroker();
Assert.IsTrue(broker.Driver.GetType() == typeof(XmlDriver));
于 2013-01-15T13:39:30.417 回答