Castle Windsor:如何使用一个实现实例注册两个服务?

发布于 2024-09-25 05:41:51 字数 281 浏览 2 评论 0原文

如何用一个实现实例注册两个服务?我使用:

 _container.Register(Component.For(new [] { typeof(IHomeViewModel), typeof(IPageViewModel) }).
            ImplementedBy(typeof(HomeViewModel)).Named("IHomeViewModel").LifeStyle.Singleton)

但是上面的代码注册了两个 HomeViewModel 实例。

How to register two services with one instance of implementation? I used:

 _container.Register(Component.For(new [] { typeof(IHomeViewModel), typeof(IPageViewModel) }).
            ImplementedBy(typeof(HomeViewModel)).Named("IHomeViewModel").LifeStyle.Singleton)

But upper code registers two instances of HomeViewModel.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

一指流沙 2024-10-02 05:41:51

这正是这样做的方法。请参阅文档中的“类型转发”。它注册一个可通过 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>());

That's exactly the way to do it. See "Type Forwarding" in the docs. It registers one logical component accessible via IHomeViewModel or IPageViewModel. The following test passes:

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 you might want to use generics instead of all those typeof, and also remove the lifestyle declaration, since singleton is the default:

container.Register(Component.For<IHomeViewModel, IPageViewModel>()
                            .ImplementedBy<HomeViewModel>());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文