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数据库从入门到精通》

相关推荐
hez201010 小时前
在 .NET 上构建超大托管数组
c#·.net·.net core·gc·clr
雨落倾城夏未凉6 天前
第四章c#方法-参数数组和可选参数(16)
后端·c#
唐青枫7 天前
线程不是越多越快:C#.NET Thread 生命周期、同步与后台工作线程实战
c#·.net
唐青枫8 天前
别只会反射:C#.NET Emit 动态生成代码实战详解
c#·.net
咕白m6258 天前
.NET 环境下 Word 超链接批量提取方案
c#·.net
用户91721561902118 天前
C# 通信协议增量解析:用状态机处理半包和粘包
c#
小码编匠9 天前
C# 工控上位机必备:数据转换工具类与十个核心模块
后端·c#·.net
唐青枫11 天前
别再乱用 StartNew:C#.NET TaskFactory 任务调度实战详解
c#·.net
Artech11 天前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf13 天前
C#摸鱼实录——IoC与DI案例详解
c#