Windsor使用密钥解析依赖关系

时间:2013-01-14 12:40:05

标签: castle-windsor

我已按照以下方式使用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,则返回正确的ID:

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));

1 个答案:

答案 0 :(得分: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));