温莎使用键解决依赖关系 [英] Windsor Resolve dependencies using a key

查看:72
本文介绍了温莎使用键解决依赖关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已通过以下方式使用温莎城堡注册了Interface的多个实例:

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

依存关系的方式如下:

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

问题是:
当我解析新的IDriver时通过以下方式使用城堡:

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

属性IDriver始终为 FileDriver 类型,而如果我解析IDriver使用密钥返回正确的密钥:

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

我该怎么说?

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


推荐答案

这是使用类型化工厂设施

只需声明工厂接口:

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

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

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

这篇关于温莎使用键解决依赖关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆