views:

13

answers:

1

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.

+1  A: 

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>());
Mauricio Scheffer
also if you're not using the name of the component (you only ever resolve it by type and don't use as named service override anywhere) you can ditch the name as well.
Krzysztof Koźmic
Thank you, problem was in my code.
INs

related questions