2015-10-15 22 views
0

使用Unity,我目前收到當試圖解決此類型的錯誤消息:統一,接口不能構建

當前類型,Onboard.UI.Services.IMessagingService,是一個接口,不能構造

下面是在我的App.xaml.cs文件中找到的代碼,它引發了此錯誤。

UnityContainer 
    .RegisterType<IMessagingService, SessionMessagingService>("SessionMessageService") 

var sessionStateNotifactionService = 
    UnityContainer 
     .Resolve <SessionStateNotificationService>("SessionMessageService"); 

我想.RegisterType<>兩個類型相同的接口IMessageService。如果我刪除了trying to register a named type的嘗試,例如參數("SessionMessageService"),一切正常;但是,我不再有辦法區分我希望使用的接口的實現方式。

該錯誤是扔在呼籲.ResolveSessionStateNotificationService構造看起來像

// ... class 

private IMessagingService _messagingService; 

public SessionStateNotificationService(IMessagingService messagingService) 
{ 
    // ... 

這裏的嘗試是更加通用的什麼實現,我可以提供給SessionStateNotificationService

有許多關於這個錯誤在計算器上,即問題:

Exception is: InvalidOperationException - The current type, is an interface and cannot be constructed. Are you missing a type mapping?

然而,問題出現的是OP做一些奇怪的事情和接受的答案是不適用於以上情況(它確實試圖遵循Unity文檔)。

我錯過了什麼?

+0

你怎麼註冊的其他' IMessagingService'? – Ric

+0

@Ric以相同的方式,以不同的名稱,例如'( 「BrowseMessageService」)'。實現(類型)是不同的。所以它看起來像'.RegisterType (「BrowseMessagService」);'但是,即使我刪除了註冊,它仍然失敗。 – Thomas

+1

你需要使用接口從我所看到和完成的'Resolve' UnityContainer.Resolve (「namehere」)' – Ric

回答

1

假設多個註冊:

UnityContainer 
    .RegisterType<IMessagingService, SessionMessagingService>("SessionMessageService") 

UnityContainer 
    .RegisterType<IMessagingService, BrowseMessagingService>("BrowseMessagingService") 

確保SessionStateNotificationService註冊並已命名的依賴存在:

UnityContainer. 
    RegisterType<SessionStateNotificationService>(
     new InjectionConstructor(new ResolvedParameter<IMessagingService>("SessionMessageService"))); 

現在解決:

UnityContainer.Resolve<SessionStateNotificationService>(); // uses the SessionMessageService