我有一个像这样的构造函数的类
public class BlotterService : IBlotterService
{
public BlotterService(IAService aService, IAnotherService anotherService)
{
// ...
}
}
和这样的注册依赖
// Default lifecycle is Singleton
Component.For<IAnotherService >().ImplementedBy<AnotherService >()
Component.For<IAService>().ImplementedBy<AService>() // instance 1 of AService
Component.For<IAService>().ImplementedBy<AService>().Named(
"aServiceAlternativeForBlotter") // instance 2 of AService
Component.For<IBlotterService>().ImplementedBy<BlotterService>()
通常,当需要IAService的类被实例化时,我想要第一个AService实例,但是在BlotterService的特定情况下,我想要AService的实例2。
如何在城堡容器中注册BlotterService / AService来实现这一目标?
编辑:更新
我正在使用Castle 2.5.1.0,遗憾的是无法升级。
答案 0 :(得分:8)
将上次注册更改为:
Component
.For<IBlotterService>()
.ImplementedBy<BlotterService>()
.DependsOn(Dependency.OnComponent(
typeof(IAService),
"aServiceAlternativeForBlotter"))
答案 1 :(得分:2)
这里有很多正确的答案,但你坚持2.5,所以我认为你需要做的是这样的:
Component.For<IBlotterService>()
.ImplementedBy<BlotterService>()
.ServiceOverrides(
ServiceOverride.ForKey("aService").Eq("aServiceAlternativeForBlotter"));
如果这不起作用,那么另一个选择是你可以创建一个从名为IAlternateService的IService派生的接口,然后依赖于它......
答案 2 :(得分:1)
在注册BlotterService期间,您需要使用覆盖指定其依赖关系。
Component.For<IBlotterService>().ImplementedBy<BlotterService>().ServiceOverrides(
new { aService = "aServiceAlternativeForBlotter" })
或者您可以使用其中一个DependsOn覆盖。