在构造函数参数中指定依赖实现

时间:2019-03-17 15:26:42

标签: .net inversion-of-control castle-windsor

假设我有一个接口IA,两个实现A1A2以及一个依赖于B的依赖类IA。在Windsor容器中,相同接口的两个实现的注册方式如下:

container.Register(Component.For<IA>()
    .ImplementedBy<A1>());
container.Register(Component.For<IA>()
    .ImplementedBy<A2>());

是否可以指定要在依赖类中使用 B的实现?

例如在Autofac中,我可以这样使用KeyFilterAttribute

class B 
{
    ...
    public B([KeyFilter("A1")]IA a)
    {
        ...
    }
}

1 个答案:

答案 0 :(得分:1)

有几种方法可以实现这一目标,哪种方法最适合取决于更大的环境。

  1. 如果您一个接一个地注册组件,例如在问题Windsor uses the first component registered as the default的示例代码中为该服务。因此,在您的B内部,您一定可以通过A1实现该服务。

  2. 为明确起见,您可以强制将组件设置为默认组件(也可以按照约定进行注册

container.Register(
   Component.For<IA>().ImplementedBy<A1>(),
   Component.For<IA>().ImplementedBy<A2>().IsDefault());
  1. 或者,从消费端的角度you can configure B to pick either A1 or A2 regardless of the defaults(最接近Autofac

container.Register(
   Component.For<B>()         
      .DependsOn(Dependency.OnComponent<IA, A1>))