前言
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();
}
}