ARTICLE · 1524051
WPF MVVM实战系列教程(七、Prism模块化)
模块化基础
首先我们了解一下插件这个概念
插件(add-in,也称为plug-in)是应用程序能够动态发现、加载和使用的单独编译过的组件。
通常,应将应用程序设计成能使用插件,从而可在将来进行增强,而不必进行主程序的任何修改、重新编译以及重新测试。
插件还为针对特殊的市场或客户单独定制应用程序实例提供了灵活性。但使用插件模型最常见的原因是,允许第三方开发人员扩展应用程序的功能。
例如,Adobe Photoshop 中的第三方滤镜插件提供了大量额外的图片处理效果。Google Chrome中的插件提供了增强的Web 冲浪特性以及全新功能。对于这两种情况,插件大多由第三方开发人员创建的。
.NET提供了MAF和MEF两种框架可以实现插件化。
MAF:https://learn.microsoft.com/en-us/dotnet/desktop/wpf/app-development/wpf-add-ins-overview
MEF:https://learn.microsoft.com/zh-cn/dotnet/framework/mef/
Prism的模块化原理就类似插件模型。它也能够动态地发现、加载和使用单独编译的组件。
在前面介绍Prism框架时,提到模块化的作用。模块化拆分、隔离与复用,核心目标都是降低应用耦合度,提升可维护性。
模块化以后
1、每个模块负责特定功能(如用户管理、订单管理),实现 “高内聚、低耦合”,便于团队协作、维护和迭代。
2、模块之间可以做到低依赖(减少直接引用,通过依赖注入实现复用),单个模块可独立编译、测试,甚至在多个应用中复用。
3、最终都能将多个独立模块整合到同一个主应用中,形成完整的功能体系,而非零散的组件。

就拿医疗行业的软件来说,它可能会划分如上的模块。不同的模块可以单独开发,测试。最后再将它们一起”组装“到”外壳“上。
对于一些基础模块,通常会定义成公用模块。需要使用的子模块可以直接引用这些基础模块。
注意:这里我们的目的是做到模块间低依赖,而不是完全没有依赖。
但是Prism的模块化和插件化会有稍许区别
Prism模块化:
模块化是 “核心架构手段”,最终目的是 “大型应用的结构化拆分与管理”。
Prism 希望在应用开发初期,就将应用拆分为多个模块,每个模块遵循统一的规范(IModule),主应用通过配置或目录扫描加载模块,便于团队分工、版本控制和后期维护。
简单来说:Prism 的模块化是为了 “事前规划”。
插件化:
最终目的是 “可扩展性”(插件化)。
当主应用发布后,无需修改主程序代码、无需重新编译,只需将新的模块(插件)放入指定目录,主应用就能自动识别并加载该模块,实现功能扩展。
简单说:插件化是为了 “事后扩展”。
模块化原则
有些小伙伴可能对这个模块的划分还存在一些困惑。
这里介绍 一下模块划分的原则
1、高内聚:一个模块只负责完成单一且明确的业务功能,不包含无关逻辑。
2、低耦合:模块之间尽量减少直接依赖,禁止跨模块直接引用View、ViewModel 或内部业务类。
3、创建独立的基础设施类库(CommonInfrastructure 项目),该项目仅包含公共接口、枚举、实体(DTO/POCO,无业务逻辑)。
这个基础设备类库是模块间交互的核心
模块加载基础原理
在Prism中涉及两种模块化的加载,一种是配置式,一种是扫描式。
配置式是显式配置,也就是主动指定要加载的模块。扫描式是隐式配置,也就是对目录进行扫描,然后自动添加符合要求的模块。
模块加载这里主要用到的是.NET的反射机制。
假设我定义了一个IModule接口(仅演示用,所以未定义具体的接口函数)
public interface IModule{}
然后我定义了一个类库LibA,增加一个类ModuleAModule继承自IModule接口
public classModuleAModule : IModule{}
再定义一个类库LibB,增加一个类ModuleBModule
public classModuleBModule{}

当我们去扫描这两个dll,通过判断是否实现了IModule接口,就可以判断是否是我们定义的模块。
简易验证过程如下:
第一步:通过 Type.GetInterface(typeof(IModule).FullName)验证该类型是否实现了IModule。第二步:验证该类型是否为 class、是否非抽象(type.IsClass && !type.IsAbstract)。
示例代码如下:
public List<Type> FindAllIModuleTypes(string moduleDirectory){var moduleTypes = new List<Type>();var assemblyFiles = Directory.GetFiles(moduleDirectory, "*.dll", SearchOption.TopDirectoryOnly);foreach (var assemblyFile in assemblyFiles){try{// 1. 加载程序集Assembly assembly = Assembly.LoadFrom(assemblyFile);// 2. 遍历程序集中的所有类型foreach (Type type in assembly.GetTypes()){// 3. 核心筛选:识别 IModule 实现类bool isValidModule = typeof(IModule).IsAssignableFrom(type) && // 实现 IModuletype.IsClass && // 是类!type.IsAbstract; // 非抽象if (isValidModule){moduleTypes.Add(type);}}}catch{// 跳过无法加载或无有效模块的程序集continue;}}return moduleTypes;}
Prism中的IModule接口
首先我们了解一下IModule接口,在Prism中,可以被加载的模块都需要实现Prism.Modularity.IModule接口。
IModule接口定义如下:
//// 摘要:// 为Prism应用程序中部署的模块定义契约。public interface IModule{//// 摘要:// 用于向容器注册应用程序将使用的类型。voidRegisterTypes(IContainerRegistry containerRegistry);//// 摘要:// 通知模块它已被初始化。voidOnInitialized(IContainerProvider containerProvider);}
IModule提供了两个接口函数:RegisterTypes和OnInitialized,可以把它理解为模块的Bootstrapper。
如何创建Prism模块
这里我们以一个简易的信息登记功能为例,增加一个Register模块,一个ViewList模块,一个CommonModule公共模块。
Register模块:登记Employee信息
ViewList模块:查看登记的Employee列表
CommonModule公共模块:定义Employee及通信事件
当在Register模块登记一个Employee后,通过ViewModel通信,将Employee添加到ViewList模块的列表中。
整体框架如下:

1、定义公用模块CommonModule
这个模块主要是用于定义Employee及通信事件。
SelectEmployeeEvent.cs
public classSelectEmployeeEvent : PubSubEvent<IEmployeeViewModel>{}
IEmployeeViewModel.cs
public interface IEmployeeViewModel{int Id { get; set; }string Name { get; set; }string Phone { get; set; }voidXXX();}
2、创建类库工程Module.Register

3、增加一个模块类RegisterModule实现IModule接口
注意:模块类在命名时,尽量以Module结尾,而且放在项目的根目录下,这样方便后期区分和查找

RegisterModule.cs
public class RegisterModule : Prism.Modularity.IModule{publicvoidOnInitialized(IContainerProvider containerProvider){}publicvoidRegisterTypes(IContainerRegistry containerRegistry){}}
这样我们就拥有了一个可以被Prism识别的模块
接下来我们对这个模块进行完善
4、添加View和ViewModel
注意:类库工程在添加View时,会找不到WPF项。

需要修改项目工程文件,添加UseWPF

添加Views\Register.xaml
这个页面用于登记
<Grid><Grid.RowDefinitions><RowDefinition/><RowDefinition/><RowDefinition/><RowDefinition/></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition/></Grid.ColumnDefinitions><LabelContent="Id"HorizontalAlignment="Right"Margin="0,0,30,0"VerticalAlignment="Center"></Label><TextBoxGrid.Row="0"Grid.Column="1"Margin="40,0"VerticalAlignment="Center"Text="{Binding EmployeeViewModel.Id}"></TextBox><LabelContent="Name"Grid.Row="1"HorizontalAlignment="Right"Margin="0,0,30,0"VerticalAlignment="Center"></Label><TextBoxGrid.Row="1"Grid.Column="1"Margin="40,0"VerticalAlignment="Center"Text="{Binding EmployeeViewModel.Name}"></TextBox><LabelContent="Phone"Grid.Row="2"HorizontalAlignment="Right"Margin="0,0,30,0"VerticalAlignment="Center"></Label><TextBoxGrid.Row="2"Grid.Column="1"Margin="40,0"VerticalAlignment="Center"Text="{Binding EmployeeViewModel.Phone}"></TextBox><ButtonContent="登记"Width="88"Height="28"HorizontalAlignment="Center"VerticalAlignment="Center"Grid.Row="3"Grid.ColumnSpan="2"Command="{Binding RegisterCommand}"></Button></Grid>
添加ViewModels\RegisterViewModel.cs
public class RegisterViewModel :BindableBase{private IEventAggregator eventAggregator;public DelegateCommand RegisterCommand { get; private set; }//EmployeeViewModel的定义请到文末示例代码中查看private EmployeeViewModel employeeViewModel = new EmployeeViewModel();public EmployeeViewModel EmployeeViewModel{get => this.employeeViewModel;set => this.SetProperty(ref employeeViewModel, value);}publicRegisterViewModel(IEventAggregator eventAggregator){RegisterCommand = new DelegateCommand(Register);this.eventAggregator = eventAggregator;}privatevoidRegister(){//点击登记时,发送消息到ViewList模块this.eventAggregator.GetEvent<SelectEmployeeEvent>().Publish(this.EmployeeViewModel);}}
5、注册模块里的视图
此时我们再回到RegisterModule类,在RegisterTypes中注册View
public class RegisterModule : Prism.Modularity.IModule{publicvoidOnInitialized(IContainerProvider containerProvider){}publicvoidRegisterTypes(IContainerRegistry containerRegistry){//注册View的时候同步绑定ViewModelcontainerRegistry.RegisterForNavigation<RegisterView, RegisterViewModel>();//也可以只注册View//然后通过ViewModelLocator.AutoWireViewModel附加属性来自动绑定ViewModel//containerRegistry.RegisterForNavigation<RegisterView>();}}
这样我们就拥有了一个完整的登记模块
然后我们按照这个逻辑,再添加ViewList模块
ViewListModule.cs
public class ViewListModule : IModule{publicvoidOnInitialized(IContainerProvider containerProvider){}publicvoidRegisterTypes(IContainerRegistry containerRegistry){//注册视图containerRegistry.RegisterForNavigation<EmployeeListView, EmployeeListViewModel>();}}
Views\EmployeeListView.xaml
<Grid><ListBoxItemsSource="{Binding EmployeeList}"><ListBox.ItemTemplate><DataTemplate><Grid><Grid.RowDefinitions><RowDefinition/><RowDefinition/></Grid.RowDefinitions><TextBlockText="{Binding Name}"HorizontalAlignment="Left"Margin="10,0,0,0"FontWeight="Bold"FontSize="13"Foreground="Blue"></TextBlock><DockPanelGrid.Row="1"Margin="0,5,0,0"><TextBlockText="Id:"Margin="10,0,5,0"></TextBlock><TextBlockText="{Binding Id}"Margin="5,0,10,0"></TextBlock><TextBlockText="Phone:"Margin="10,0,5,0"></TextBlock><TextBlockText="{Binding Phone}"FontStyle="Italic"></TextBlock></DockPanel></Grid></DataTemplate></ListBox.ItemTemplate></ListBox></Grid>
ViewModels\EmployeeListViewModel.cs
public class EmployeeListViewModel : BindableBase{//列表private ObservableCollection<IEmployeeViewModel> employeeList = new ObservableCollection<IEmployeeViewModel>();public ObservableCollection<IEmployeeViewModel> EmployeeList{get => this.employeeList;set => this.SetProperty(ref employeeList, value);}publicEmployeeListViewModel(IEventAggregator eventAggregator){//创建登记界面发送数据订阅eventAggregator.GetEvent<SelectEmployeeEvent>().Subscribe(OnAddEmployee);}//接收从登记界面发送过来的数据privatevoidOnAddEmployee(IEmployeeViewModel model){this.EmployeeList.Add(model);}}
Prism模块加载流程
Prism模块加载流程如下图所示

这里我们了解一下IModuleCatalog接口和IModuleManager接口。
IModuleCatalog接口
IModuleCatalog 是模块清单,负责 “记录” 应用中有哪些模块、加载规则和依赖关系,是静态的元数据存储;
///<summary>/// 这是ModuleManager的预期目录定义。ModuleCatalog包含应用程序可使用的模块信息。/// 每个模块都在ModuleInfo类中进行了描述,该类记录了模块的名称、类型和位置。///</summary>public interface IModuleCatalog{///<summary>/// 获取IModuleCatalog中的所有IModuleInfo类型///</summary>IEnumerable<IModuleInfo> Modules { get; }IEnumerable<IModuleInfo> GetDependentModules(IModuleInfo moduleInfo);IEnumerable<IModuleInfo> CompleteListWithDependencies(IEnumerable<IModuleInfo> modules);///<summary>/// 初始化目录,这可能会加载并验证模块。///</summary>voidInitialize();///<summary>/// 将IModuleInfo添加到IModuleCatalog中///</summary>IModuleCatalog AddModule(IModuleInfo moduleInfo);}
它会在Bootstrapper初始化时,进行初始化。过程如下所示:
public abstract class PrismApplicationBase : Application{protectedoverridevoidOnStartup(StartupEventArgs e){InitializeInternal();}voidInitializeInternal(){Initialize();}protectedvirtualvoidInitialize(){_moduleCatalog = CreateModuleCatalog();}protectedvirtual IModuleCatalog CreateModuleCatalog(){return new ModuleCatalog();}}
IModuleManager
IModuleManager 是模块加载器,负责 “执行” 模块的加载和初始化,支持立即加载和按需加载,是动态的操作组件;
///<summary>/// Defines the interface for the service that will retrieve and initialize the application's modules.///</summary>public interface IModuleManager{///<summary>/// Gets all the <see cref="IModuleInfo"/> classes that are in the <see cref="IModuleCatalog"/>.///</summary>IEnumerable<IModuleInfo> Modules { get; }///<summary>/// Initializes the modules marked as <see cref="InitializationMode.WhenAvailable"/> on the <see cref="IModuleCatalog"/>.///</summary>voidRun();///<summary>/// Loads and initializes the module on the <see cref="IModuleCatalog"/> with the name <paramref name="moduleName"/>.///</summary>///<param name="moduleName">Name of the module requested for initialization.</param>voidLoadModule(string moduleName);///<summary>/// Raised repeatedly to provide progress as modules are downloaded.///</summary>event EventHandler<ModuleDownloadProgressChangedEventArgs> ModuleDownloadProgressChanged;///<summary>/// Raised when a module is loaded or fails to load.///</summary>event EventHandler<LoadModuleCompletedEventArgs> LoadModuleCompleted;}
IModuleManager也是在Bootstrapper初始化时进行初始化,调用流程如下所示
public abstract class PrismApplicationBase : Application{protectedoverridevoidOnStartup(StartupEventArgs e){InitializeInternal();}voidInitializeInternal(){Initialize();}protectedvirtualvoidInitialize(){RegisterRequiredTypes(_containerExtension);}protectedvirtualvoidRegisterRequiredTypes(IContainerRegistry containerRegistry){//注入IModuleManager单例containerRegistry.RegisterSingleton<IModuleManager, ModuleManager>();}}
如何加载Prism模块
经过上述步骤,我们就创建好了两个Prism模块。接下来我们需要做的就是把它们加载到主窗口(Shell),然后一起工作。
Prism提供了5种加载模块的方法:
1、代码加载
2、目录扫描
3、手动加载
4、Xaml加载
5、AppConfig加载
这里的话只介绍前面三种方式,因为就我目前实际开发情况来看,后面两种方法用到的相对较少。
感兴趣的可以参考下面的代码自行学习:
https://github.com/PrismLibrary/Prism-Samples-Wpf/tree/master/07-Modules-AppConfig(AppConfig加载)
https://github.com/PrismLibrary/Prism-Samples-Wpf/tree/master/07-Modules-Xaml(Xaml加载)
代码加载
实现步骤如下:
1、在Shell工程上添加模块项目引用

引用我们需要使用的Prism模块项目

2、在Shell(MainWindow)的Bootstrapper中重写ConfigureModuleCatalog函数,配置要加载的模块
protectedoverridevoidConfigureModuleCatalog(IModuleCatalog moduleCatalog){//添加模块引用moduleCatalog.AddModule<RegisterModule>();moduleCatalog.AddModule<ViewListModule>();}
3、在Shell(MainWindow)的Bootstrapper中加载View
protectedoverridevoidOnInitialized(){base.OnInitialized();var regionManager = this.Container.Resolve<IRegionManager>();regionManager.RegisterViewWithRegion("EditArea", typeof(RegisterView));regionManager.RegisterViewWithRegion("ListArea", typeof(EmployeeListView));}
在前面我介绍介绍过,RegisterViewWithRegion函数可以绑定默认视图。
现在就等于将RegisterView绑定到EditArea区域,将EmployeeListView绑定到ListArea区域。
而RegisterView和EmployeeListView都分别来自于不同的模块。
程序运行效果如下:


可以看到,这些功能虽然不是在一个模块里定义的,但最终可以被组装到一起,实现一个完整的功能 。
目录扫描
目录扫描主要是通过指定一个目录,然后Prism框架自动去扫描目录中符合要求的Prism模块。
实现步骤如下:
1、将模块输出到固定位置
例如我们将前面的两个模块输出到Modules目录下
Modules目录

项目输出路径

2、配置目录加载
public partial class App : PrismApplication{protectedoverride Window CreateShell(){return Container.Resolve<MainWindow>();}protectedoverridevoidRegisterTypes(IContainerRegistry containerRegistry){}protectedoverride IModuleCatalog CreateModuleCatalog(){//指定目录//可以使用相对路径也可以使用绝对路径//推荐相对路径return new DirectoryModuleCatalog() { ModulePath = @".\Modules" };}}
说明:在功能模块明确的情况下,推荐使用代码加载方式加载模块。有时候我们想动态扩展一些功能,可以使用目录加载。例如我有一款设备,在出厂时只有A型号,后期可能会增加B、C型号,或者更多。
手动加载
手动加载的整体流程和代码加载是一样的,都是需要引用项目工程。
在前面我们介绍了IModuleManager接口,它会在Bootstrapper初始化时,自动注入到容器中
手动加载模块主要用到IModuleManager接口。
实现步骤如下:
1、在Shell中增加一个按钮,用于手动加载模块
<Grid><Grid.RowDefinitions><RowDefinitionHeight="35"/><RowDefinition/></Grid.RowDefinitions><GridGrid.Row="0"><ButtonContent="加载模块"HorizontalAlignment="Center"VerticalAlignment="Center"Width="88"Height="28"Command="{Binding ManualLoadModuleCommand}"/></Grid><GridGrid.Row="1"><Grid.ColumnDefinitions><ColumnDefinition/><ColumnDefinition/></Grid.ColumnDefinitions><ContentControlprism:RegionManager.RegionName="EditArea"></ContentControl><ContentControlprism:RegionManager.RegionName="ListArea"Grid.Column="1"></ContentControl></Grid></Grid>
2、在Shell工程上添加模块项目引用

引用我们需要使用的Prism模块项目

3、在Bootstrapper中重写ConfigureModuleCatalog函数,添加模块到IModuleCatalog中
public partial class App : PrismApplication{protectedoverride Window CreateShell(){return Container.Resolve<MainWindow>();}protectedoverridevoidRegisterTypes(IContainerRegistry containerRegistry){}///<summary>/// 配置模块///</summary>///<param name="moduleCatalog"></param>protectedoverridevoidConfigureModuleCatalog(IModuleCatalog moduleCatalog){var moduleRegisterType = typeof(RegisterModule);var moduleViewListType = typeof(ViewListModule);moduleCatalog.AddModule(new ModuleInfo(){ModuleName = moduleRegisterType.Name,ModuleType = moduleRegisterType.AssemblyQualifiedName,InitializationMode = InitializationMode.OnDemand //需要时再加载});moduleCatalog.AddModule(new ModuleInfo(){ModuleName = moduleViewListType.Name,ModuleType = moduleViewListType.AssemblyQualifiedName,InitializationMode = InitializationMode.OnDemand //需要时再加载});}}
4、在需要加载的地方,使用IModuleManager接口的LoadModule函数手动执行加载
///<summary>/// 手动加载模块///</summary>privatevoidManualLoadModule(){this.moduleManager.LoadModule("RegisterModule");this.moduleManager.LoadModule("ViewListModule");}
运行效果

示例代码
https://github.com/zhaotianff/WPF-MVVM-Beginner/tree/main/15_Prism_Module.sln
你可能还想看:

01

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

Happy Time


Win开发者
[
粉丝微信群
].

github丨https://github.com/zhaotianff















































































