PRISM MEF中模块和壳牌之间的通信

本文关键字:之间 通信 MEF 模块 PRISM | 更新日期: 2023-09-27 18:35:28

我有一个模块,接口为IModuleMainService,有一个事件。

例如 [Export(typeof(IModuleMainService))]

我有带有接口IMainService的SHELL。

例如 [Export(typeof(IMainService))]

在模块主中,我有导入[Import(typeof(IMainService)]

在这种情况下,应用程序可以工作,但我想与模块和外壳进行通信。

我尝试将导入插入到壳牌.cs例如

[Import]
public IModuleMainService ModuleMainService { get; set; }

但是我运行应用程序并出现错误,请参见下文。如果我评论[Import] public IModuleMainService...应用程序运行成功。问题在哪里?

重点是:SHELL 中模块类的消耗事件。

System.ComponentModel.Composition 警告: 1 : ComposablePartDefinition 'Main.Silverlight.Views.Shell' 已被拒绝。组成保持不变。由于以下错误,更改被拒绝:合成产生了单个合成错误。根本原因如下。查看 CompositionException.Errors 属性以获取更多详细信息。

1) 未找到与约束 '((exportDefinition.ContractName == "Main.ViewModels.ShellViewModel") 和 (exportDefinition.Metadata.ContainsKey("ExportTypeIdentity") 以及 "Main.ViewModels.ShellViewModel" 匹配的有效导出。等于(exportDefinition.Metadata.get_Item("导出类型标识"))))',无效的导出可能已被拒绝。

导致:无法在部分"Main.Silverlight.Views.Shell"上设置导入"Main.Silverlight.Views.Shell.ViewModel (ContractName="Main.ViewModels.ShellViewModel")"。元素: Main.Silverlight.Views.Shell.ViewModel (contractName="Main.ViewModels.ShellViewModel") --> Main.Silverlight.Views.Shell --> AssemblyCatalog (Assembly="Main, version=1.0.0.0, culture=neutral, PublicKeyToken=null")

类型为"System.ComponentModel.Composition.ImportCardinalityMismatchException"的第一次机会异常发生在System.ComponentModel.Composition中

PRISM MEF中模块和壳牌之间的通信

在棱镜编程中,模块和外壳应分开。不得声明从一个模块到另一个模块或 shell 的直接引用。你需要做的是使用EventAggregator,以便在模块或 shell 之间交换消息。

使用

IEventAggregator 的替代方法是使用 RegionScopes 传递消息。

总而言之,不要在模块和 shell 之间创建直接引用;使用 IEventAggregator 交换消息,并在公共库中声明消息携带事件,该库被所有模块和 shell 重用。