如何用一个实现实例注册两个服务?我用了:
_container.Register(Component.For(new [] { typeof(IHomeViewModel), typeof(IPageViewModel) }).
ImplementedBy(typeof(HomeViewModel)).Named("IHomeViewModel").LifeStyle.Singleton)
但是上面的代码注册了两个 HomeViewModel 实例。
如何用一个实现实例注册两个服务?我用了:
_container.Register(Component.For(new [] { typeof(IHomeViewModel), typeof(IPageViewModel) }).
ImplementedBy(typeof(HomeViewModel)).Named("IHomeViewModel").LifeStyle.Singleton)
但是上面的代码注册了两个 HomeViewModel 实例。
这正是这样做的方法。请参阅文档中的“类型转发”。它注册一个可通过 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>());
}
顺便说一句,您可能想使用泛型而不是所有这些typeof
,并删除生活方式声明,因为单例是默认设置:
container.Register(Component.For<IHomeViewModel, IPageViewModel>()
.ImplementedBy<HomeViewModel>());