我自己从未使用过 Prism+MEF,但在您的问题中您提到您希望能够在运行时加载模块(使用 MEF)。这是您不需要 MEF 的事情,因为 Prism 本身就非常擅长这样做。设置非常简单:
首先,通过实现创建一个 Prism 模块Modularity.IModule
。它只需要一种方法:Initialize()
. 在这里,您可以进行模块所需的任何设置。我通常还会扩展构造函数以注入我可能需要的任何其他接口(使用 Unity)。
然后,创建一个 ModuleCatalog 来指定您创建的模块的详细信息:
<Modularity:ModuleCatalog
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Modularity="clr-namespace:Microsoft.Practices.Prism.Modularity;assembly=Microsoft.Practices.Prism.Composition">
<Modularity:ModuleInfo Ref="Your.ModuleProject.dll"
ModuleType="Your.ModuleProject.Module, Your.ModuleProject"
ModuleName="Module1"
InitializationMode="OnDemand" />
</Modularity>
如果您需要运行时加载,这InitializationMode
是您想要设置的。目录可以在 Prim 引导程序中加载:
catalog = Microsoft.Practices.Prism.Modularity.ModuleCatalog.CreateFromXaml(new Uri("Modules.xaml", UriKind.RelativeOrAbsolute));
然后你需要做的就是加载你的模块,得到一个引用IModuleManager
(依赖注入,耶!)并加载模块:
if (loadModule1)
var myModule = moduleManager.LoadModule("Module1");
现在该模块已为 Prism 所知。请记住,Prism 不支持卸载。