Microsoft Unity中转发的类型

时间:2010-09-21 09:34:22

标签: .net castle-windsor unity-container

如何在Unity Framework中将单个组件用于多个服务?

在Windsor中,它按以下方式配置:

var container = new WindsorContainer();
container.Register(Component.For<Service1, Service2>()
                            .ImplementedBy<Component>());

var service1 = container.Resolve<Service1>();
var service2 = container.Resolve<Service2>();

转发类型的想法是,如果组件是单个service1service2 是相同的实例

2 个答案:

答案 0 :(得分:3)

此测试通过:

[Fact]
public void ContainerCorrectlyForwards()
{
    var container = new UnityContainer();
    container.RegisterType<IService1, MyComponent>(
        new ContainerControlledLifetimeManager());
    container.RegisterType<IService2, MyComponent>(
        new ContainerControlledLifetimeManager());

    var service1 = container.Resolve<IService1>();
    var service2 = container.Resolve<IService2>();

    Assert.Same(service1, service2);
}

答案 1 :(得分:0)

AFAIK,您不能:您必须使用相同的映射组件注册每个服务:

container.RegisterType<Service1, Component>(new ContainerControlledLifetimeManager())
         .RegisterType<Service2, Component>(new ContainerControlledLifetimeManager())