Unity,接口无法构建

Unity, Interface Cannot Be Constructed

使用 Unity,我目前在尝试解析类型时收到此错误消息:

The current type, Onboard.UI.Services.IMessagingService, is an interface and cannot be constructed

下面是在我的 App.xaml.cs 文件中找到的引发此错误的代码。

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

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

我正在尝试 .RegisterType<> 共享同一接口 IMessageService 的两种类型。如果我删除 trying to register a named type 处的尝试,例如("SessionMessageService") 参数,一切正常;但是,我不再有办法区分我希望使用的接口实现。

调用 .Resolve 时抛出错误,因为 SessionStateNotificationService 的构造函数看起来像

// ... class

private IMessagingService _messagingService;

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

这里的尝试是更通用地说明我可以为 SessionStateNotificationService 提供哪些实现。

在 Whosebug 上有很多关于此错误的问题,即:

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

但是,这个问题是由于该 OP 做了一些奇怪的事情而产生的,并且接受的答案不适用于上述情况(实际上是在尝试遵循 Unity 文档)。

我错过了什么?

假设多次注册:

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