如何使用一个实现实例注册两个服务?我用过:
_container.Register(Component.For(new [] { typeof(IHomeViewModel), typeof(IPageViewModel) }).
ImplementedBy(typeof(HomeViewModel)).Named("IHomeViewModel").LifeStyle.Singleton)
但是上层代码注册了两个HomeViewModel实例。
答案 0 :(得分:7)
这正是这样做的方式。请参阅文档中的“Type Forwarding”。它注册了一个可通过IHomeViewModel或IPageViewModel访问的逻辑组件。以下测试通过:
public interface IHomeViewModel {}
public interface IPageViewModel {}
public class HomeViewModel: IHomeViewModel, IPageViewModel {}
[Test]
public void Forward() {
var container = new WindsorContainer();
container.Register(Component.For(new[] {typeof (IHomeViewModel), typeof (IPageViewModel)})
.ImplementedBy(typeof(HomeViewModel)).Named("IHomeViewModel").LifeStyle.Singleton);
Assert.AreSame(container.Resolve<IHomeViewModel>(), container.Resolve<IPageViewModel>());
}
BTW你可能想要使用泛型而不是所有那些typeof
,并且还删除了生活方式声明,因为单身是默认的:
container.Register(Component.For<IHomeViewModel, IPageViewModel>()
.ImplementedBy<HomeViewModel>());