Castle Windsor ChildContainer依赖决议

时间:2017-12-22 12:12:32

标签: dependency-injection inversion-of-control castle-windsor

我正在使用Castle Windsor,这就是我想做的事。

ParentContainerCarFactory取决于摘要WheelFactory,但WheelFactory将在子容器1和2中注册

ChildContainer 1 WheelFactoryBigWheelFactory ChildContainer 2 WheelFactorySmallWheelFactory

现在我们有[ParentContainer (ChildContainer 1, ChildContainer 2)]

主题1 仅使用ChildContainer 1

主题2 仅使用ChildContainer 2

主题1 CarFactory询问ChildContainer 1,在这种情况下,汽车制造厂应使用BigWheelFactory

主题2 CarFactory询问ChildContainer 2,在这种情况下,汽车工厂应使用SmallWheelFactory

如何通过Castle Windsor实现这一目标。即使手段不使用子容器

1 个答案:

答案 0 :(得分:1)

而不是子容器尝试标准服务覆盖:

var container = new WindsorContainer();

container.Register(Component.For<HostForThread1>().DependsOn(Property.ForKey<CarFactory>().Is("CarFactory1")));
container.Register(Component.For<HostForThread2>().DependsOn(Property.ForKey<CarFactory>().Is("CarFactory2")));

container.Register(Component.For<CarFactory>().DependsOn(Property.ForKey<WheelFactory>().Is<BigWheelFactory>()).Named("CarFactory1"));
container.Register(Component.For<CarFactory>().DependsOn(Property.ForKey<WheelFactory>().Is<SmallWheelFactory>()).Named("CarFactory2"));

container.Register(Component.For<WheelFactory>().ImplementedBy<BigWheelFactory>());
container.Register(Component.For<WheelFactory>().ImplementedBy<SmallWheelFactory>());


public class HostForThread1
{
    public HostForThread1(CarFactory factory)
    {
        this.Factory = factory;
    }

    public CarFactory Factory { get; }
}

public class HostForThread2
{
    public HostForThread2(CarFactory factory)
    {
        this.Factory = factory;
    }

    public CarFactory Factory { get; }
}

public class CarFactory
{
    public CarFactory(WheelFactory wheelFactory)
    {
        this.WheelFactory = wheelFactory;
    }

    public WheelFactory WheelFactory { get; }
}

public abstract class WheelFactory
{
}

public class BigWheelFactory : WheelFactory
{
}

public class SmallWheelFactory : WheelFactory
{
}