Windsor Resolve dependencies using a key

吃可爱长大的小学妹 提交于 2019-12-11 06:48:08

问题


I have registered multiple instances of an Interface using castle Windsor in the following way:

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

The dependencies are in the following way:

+ IBroker
  - IDriver
    types
    {
     - FileDriver
     - XmlDriver
    }
  - ISerializerAdapter

So in order to create a new object, this is the default constructor order:

IBroker broker = new Broker(new IDriver(new ISerializerAdapter));

The question is: When I resolve a new IDriver using castle in the following way:

IBroker broker = container.Resolve<IBroker>();
IDriver driver = broker.Driver;
Assert.IsTrue(driver.GetType() == typeof(FileDriver));

The property IDriver is always of type FileDriver, while if I resolve the IDriver using the key it return the proper one:

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

How can I say something like this?

IBroker broker = container.Resolve<IBroker>("Xml");
Assert.IsTrue(broker.Driver.GetType() == typeof(XmlDriver));

回答1:


This is typical scenario to use Typed Factory Facility.

Just declare factory interface:

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

And register it like this:

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"),

The GetXxx() method name should match with .Named("Xxx"), thats all. Usage:

var factory = container.Resolve<IBrokerFactory>();
IBroker broker = factory.GetXmlBroker();
Assert.IsTrue(broker.Driver.GetType() == typeof(XmlDriver));


来源:https://stackoverflow.com/questions/14318582/windsor-resolve-dependencies-using-a-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!