2010-09-30 72 views
3

如何使用一個實施實例註冊兩個服務?我用過:Castle windsor:如何使用一個實施實例註冊兩個服務?

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

但是上面的代碼註冊了兩個HomeViewModel實例。

回答

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>()); 
} 

順便說一句,你可能要改爲使用泛型的所有typeof,並且還去掉生活方式的聲明,因爲單是默認:

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

還,如果你不使用組件的名稱(你只能通過類型解決它,並且不要在任何地方使用命名服務覆蓋),那麼也可以忽略該名稱。 – 2010-09-30 21:47:33

+0

謝謝,問題出在我的代碼中。 – INs 2010-10-01 12:47:59

相關問題