MefBootstrapper在Prism引导程序中的使用

前言

MefBootstrapper 是使用 MEF(Managed Extensibility Framework)作为依赖注入容器的 Prism 引导程序。

1、创建Bootstrapper引导程序类

CreateShell方法用于从容器中获取主窗口;InitializeShell中用于设置主窗体以及显示主窗体,注意这里要引用Prism.Mef.Wpf.dll。

csharp 复制代码
 class BootStrapper : MefBootstrapper
    {
        private readonly string ApplicationPath = Environment.CurrentDirectory + "\\lib\\";
        protected override DependencyObject CreateShell()
        {
            return this.Container.GetExportedValue<MyShell>();
        }
        protected override void InitializeShell()
        {
            base.InitializeShell();
            Application.Current.MainWindow = (Window)Shell;
            Application.Current.MainWindow.Show();
        }

        protected override void ConfigureAggregateCatalog()
        {
            base.ConfigureAggregateCatalog();
            this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(BootStrapper).Assembly));
            DirectoryCatalog catalog = new DirectoryCatalog(ApplicationPath);
            this.AggregateCatalog.Catalogs.Add(catalog);
        }
        protected override void ConfigureModuleCatalog()
        {
            base.ConfigureModuleCatalog();
        }
    }
csharp 复制代码
启动流程
Application.Startup()
    ↓
BootStrapper 实例化
    ↓
CreateLogger() - 创建日志
    ↓
ConfigureModuleCatalog- 配置模块目录
    ↓
ConfigureAggregateCatalog- 配置组件目录
    ↓
CreateShell() - 创建主窗口
    ↓
InitializeShell() - 初始化主窗口
    ↓
InitializeModules() - 初始化所有模块
    ↓
应用程序就绪

2、使用引导程序

1)删除 StartupUri

2)重写OnStartup方法

在App.xaml.cs类中重写OnStartup方法,实例化BootStrapper类,并调用Run方法

3、导出主窗体MyShell类

csharp 复制代码
  public partial class App : Application
    {

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
            BootStrapper bootStrapper = new BootStrapper();
            bootStrapper.Run();
        }
    }

马工撰写的年入30万+C#上位机项目实战必备教程(点击下方链接即可访问文章目录)

1、《C#串口通信从入门到精通》

2、《C#与PLC通信从入门到精通 》

3、《C# Modbus通信从入门到精通》

4、《C#Socket通信从入门到精通 》

5、《C# MES通信从入门到精通》

6、《winform控件从入门到精通》

7、《C#操作MySql数据库从入门到精通》

相关推荐
大G的笔记本16 小时前
生产级 Spring Boot 网关简单实现方案
wpf
leo__52021 小时前
C# 虚拟键盘(软键盘)实现
单片机·c#·计算机外设
周杰伦fans1 天前
AutoCAD C# 二次开发:如何精确监听工作空间切换事件
前端·c#
用户3721574261351 天前
如何使用 C# 自动调整 Excel 行高和列宽
c#
AI导出鸭PC端1 天前
智谱清言怎么生成word文档?AI导出鸭终结乱码烦恼
人工智能·ai·c#·word·豆包·ai导出鸭
xiaoshuaishuai81 天前
C# AvaloniaUI 中旋转
开发语言·c#
weixin_428005301 天前
C#调用 AI学习从0开始-第2阶段(Function Calling+工具调用智能体)-第9天实战-实现计算器工具
开发语言·学习·c#·functioncalling·ai实现计算器工具
guygg881 天前
基于C# + Halcon的通用ROI绘制工具
stm32·单片机·c#
双河子思1 天前
《代码整洁之道》——读书笔记(持续更新)
开发语言·c++·c#
诙_1 天前
unity——C#
unity·c#·游戏引擎