[英]Castle Windsor injection of specific component
我可能对此太想了。 希望如此。
在我们的.Net 4.5,C#5 Windows服务中,我们使用已安装CollectionResolver
Castle Windsor 3.2。 我们有一个IEncryptionService
接口,它IEncryptionService
您的期望,并且有两个类实现了该接口。 该服务需要通过解密一个系统中的数据并为另一个系统重新加密来集成和桥接其他两个系统。
两种实现都有根据其目标系统的名称。
Component.For<IEncryptionService>()
.ImplementedBy<System1EncryptionService>()
.Named("system1-encryption")
.LifestyleTransient(),
Component.For<IEncryptionService>()
.ImplementedBy<System2EncryptionService>()
.LifestyleTransient()
.Named("system2-encryption"));
Windows服务类使用构造函数注入来接收IEncryptionService[]
类型的数组。 两种加密类都将被注入。
问题就出在这里:我需要对一个系统使用一个实现,对另一个系统使用另一个实现。 到目前为止,我实现它的方式彼此之间是无法区分的。
这里有什么解决方案? 一个有类型的工厂似乎是一种反模式,掩盖了建筑缺陷。 但这是我唯一想到的。 我已经命名了我的组件; 我可以在其他组件中利用它吗? 还是我应该忘记注入并直接实例化它们?
我认为这种情况经常发生,以至于可能存在一种标准的处理方式。
注册依赖于这两个组件的组件时,可以在Compnent.For
行中指定与注入的类相对应的参数名称:
Component.For<IServiceUsingTheEncryption>()
.ImplementedBy<ServiceUsingTheEncryption>()
//.LifestyleOfYourChoosing
.ServiceOverrides(
ServiceOverride.ForKey("encryptionService1").Eq("system1-encryption"),
ServiceOverride.ForKey("encryptionService2").Eq("system2-encryption"));
在ServiceUsingTheEncryption的ctor
中,您可以这样指定参数:
public ServiceUsingTheEncryption(IEncryptionService encryptionService1, IEncryptionService encryptionService2) {
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.