Windsor Castle: How to register two services with one instance of implementation?

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

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

But the top code registers two instances of HomeViewModel.

+3
source share
1 answer

That is exactly so. See β€œ Type Forwarding” in the docs. It registers one logical component, accessible through 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>());
}

By the way, you can use generics instead of all of these typeof, and also remove the lifestyle declaration, since singleton is the default:

container.Register(Component.For<IHomeViewModel, IPageViewModel>()
                            .ImplementedBy<HomeViewModel>());
+7
source

Source: https://habr.com/ru/post/1767345/


All Articles