Bootstrapper就是Prism的引导程序,我们知道在Composite UI Application Block时我们是通过继承FormShellApplication来引导我们的程序,它们的职责是一样的,它会为我们的程序做一些初始化的工作。如下图:
它按照上面的顺序帮我们做一些初始化工作,下面是Bootstrapper的类图
Bootstrapper里没有方法的执行步骤,所有的执行顺序由子类定义。
Bootstrapper里并不含Container,这是因为在4.0版本之前并由于只有一个UnitBootstrapper,并没有为它定义基类,它使用UnitContainer作为它的依赖注入容器,虽然宣称支持第三方的依赖注入如Spring.net,但Sprint.net不可能继承IUnityContainer,这意味着你不能使用UnitBootstrapper,你需要把UnitBootstrapper的功能全部重写,而且没有基本供你继承。我认为这是设计时的失误,在4.0时由于增加了MefBootstrapper,所以才有了这个基本。也有我们扩展自己的Bootstrapper提供了方便。
Bootstrapper在ConfigureRegionAdaperMappings中注册了一些默认的RegionAdaper,
regionAdapterMappings.RegisterMapping(typeof(Selector), ServiceLocator.Current.GetInstance<SelectorRegionAdapter>());
regionAdapterMappings.RegisterMapping(typeof(ItemsControl), ServiceLocator.Current.GetInstance<ItemsControlRegionAdapter>());
regionAdapterMappings.RegisterMapping(typeof(ContentControl), ServiceLocator.Current.GetInstance<ContentControlRegionAdapter>());
如果我们自定义了自己的Region,需求在重写这个方法注册自己的RegionAdapter
我们看一下这二个引导程序的
UnitBootstrapper在Run方法中的执行顺序大致如下
CreateModuleCatalog();
ConfigureModuleCatalog()CreateContainer()
这些方法都是虚方法,我们根据需要重写这些方法,提供我们的Container、Module、Shell等。
MefBootstrapper的执行顺序和UnitBootstrapper的类似,只是多了二步CreateAggregateCatalog()和ConfigureAggregateCatalog()
下面看一下使用的例子,我们知道在WPF中通过App.XAML中的StartURL指定程序的MainWindows,这里我们需要用在我们需要在创建主窗体前做一些初始化工作,所以我们在删除StartURL,用Bootstrapper来创建主窗体。
我们继承UnitBootStrapper
Bootstrapper class Bootstrapper : UnityBootstrapper { protected override DependencyObject CreateShell() { return this.Container.Resolve<Shell>(); } protected override void InitializeShell() { base.InitializeShell(); App.Current.MainWindow = (Window)this.Shell; App.Current.MainWindow.Show(); } protected override void ConfigureModuleCatalog() { base.ConfigureModuleCatalog(); ModuleCatalog moduleCatalog = (ModuleCatalog)this.ModuleCatalog; moduleCatalog.AddModule(typeof(HelloWorldModule.HelloWorldModule)); } }
代码很简单,在ConfigureModuleCatalog中增加HelloWorldModule,创建Shell,并且指定它为App的MainWindows.
我们在App的OnStartup方法中创建Bootstrapper并且调用他的Run方法即可.
Shell的定义如下
Shell<Window x:Class="HelloWorld.Shell" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:cal="http://www.codeplex.com/CompositeWPF" Title="Hello World" Height="300" Width="300"> <ItemsControl Name="MainRegion" cal:RegionManager.RegionName="MainRegion" /> </Window>
在Shell中指定了一个MaiRegion,
在HelloWordModule中我们指定按HelloWordView显示在MainRegion中
HelloWorldModule public class HelloWorldModule : IModule { private readonly IRegionViewRegistry regionViewRegistry; public HelloWorldModule(IRegionViewRegistry registry) { this.regionViewRegistry = registry; } public void Initialize() { regionViewRegistry.RegisterViewWithRegion("MainRegion", typeof(Views.HelloWorldView)); } }
这样一个HelloWorld的程序就完成了,由于只是说Bootstrapper,所有用了Prism中最简单的HelloWord示例,代码在Prism中有.
以后我们会试下自定义一个Bootstrapper,这里只是一个入门