我正在使用Castle Windsor,这就是我想做的事。
ParentContainer
有CarFactory
取决于摘要WheelFactory
,但WheelFactory
将在子容器1和2中注册
ChildContainer 1
WheelFactory
为BigWheelFactory
ChildContainer 2
WheelFactory
为SmallWheelFactory
现在我们有[ParentContainer (ChildContainer 1, ChildContainer 2)]
主题1 仅使用ChildContainer 1
主题2 仅使用ChildContainer 2
主题1 从CarFactory
询问ChildContainer 1
,在这种情况下,汽车制造厂应使用BigWheelFactory
。
主题2 从CarFactory
询问ChildContainer 2
,在这种情况下,汽车工厂应使用SmallWheelFactory
。
如何通过Castle Windsor实现这一目标。即使手段不使用子容器
答案 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
{
}