3.Bootstrapper(引导程序)
引导程序负责引导您的应用程序。它配置 IoC 容器,创建根 ViewModel
的新实例并使用WindowManager
。它还提供各种其他功能,如下所述。
引导程序有两种风格:BootstrapperBase<TRootViewModel>
需要您自己配置 IoC 容器,以及Bootstrapper<TRootViewModel>
使用 Stylet 的内置 IoC 容器 StyletIoC
。
示例引导程序,使用 StyletIoC:
class Bootstrapper : Bootstrapper<MyRootViewModel>
{
protected override void OnStart()
{
// 在应用程序启动后,但在设置 IoC 容器之前调用此方法。
//设置日志记录等
}
protected override void ConfigureIoC(IStyletIoCBuilder builder)
{
// 绑定你自己的类型。 具体类型是自动自绑定的。
builder.Bind<IMyInterface>().To<MyType>();
}
protected override void Configure()
{
// 这在 Stylet 创建 IoC 容器之后调用,因此 this.Container 存在,但在
// 启动根 ViewModel。
// 在这里配置你的服务等
}
protected override void OnLaunch()
{
// 这是在根 ViewModel 启动后立即调用的
// 可能会从这里启动显示对话框的版本检查之类的东西
}
protected override void OnExit(ExitEventArgs e)
{
// 在 Application.Exit 上调用
}
protected override void OnUnhandledException(DispatcherUnhandledExceptionEventArgs e)
{
// 在 Application.DispatcherUnhandledException 上调用
}
}
使用自定义 IoC 容器
将另一个 IoC 容器与 Stylet 一起使用很容易。我在Bootstrappers 项目中包含了许多流行的 IoC 容器的引导程序。这些都是经过单元测试但未经实战测试的:随意定制它们。
请注意,Stylet nuget 包/dll 不包含这些,因为它会添加不必要的依赖项。同样,我不发布特定于 IoC 容器的包,因为那是浪费精力。
将您想要的引导程序从上面的链接复制到您的项目中的某个地方。然后子类化它,就像你通常子类化的那样Bootstrapper,上面记录。然后将您的子类添加到您的 App.xaml.cs,如Quick Start 快速开始中所述,例如
public class Bootstrapper : AutofacBootstrapper<ShellViewModel>
{
}
<Application x:Class="Stylet.Samples.Hello.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:s="https://github.com/canton7/Stylet"
xmlns:local="clr-namespace:Stylet.Samples.Hello">
<Application.Resources>
<s:ApplicationLoader>
<s:ApplicationLoader.Bootstrapper>
<local:Bootstrapper/>
</s:ApplicationLoader.Bootstrapper>
</s:ApplicationLoader>
</Application.Resources>
</Application>
如果您想为另一个 IoC 容器编写自己的引导程序,那也很容易。看看上面的引导程序,看看你需要做什么。
将资源字典添加到 App.xaml
s:ApplicationLoader
本身就是一个 ResourceDictionary
。如果需要将自己的资源字典添加到 App.xaml
,则必须将 s:ApplicationLoader
作为 MergedDictionary
嵌套在 ResourceDictionary
中,如下所示:
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<s:ApplicationLoader>
<s:ApplicationLoader.Bootstrapper>
<local:Bootstrapper/>
</s:ApplicationLoader.Bootstrapper>
</s:ApplicationLoader>
<ResourceDictionary Source="YourDictionary.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Application.Resources>
项目原地址:https://github.com/canton7/Stylet
当前文档原地址:https://github.com/canton7/Stylet/wiki/Bootstrapper
上一篇:WPF的MVVM框架Stylet开发文档 2. Quick Start快速开始
下一篇:WPF的MVVM框架Stylet开发文档 4. 视图模型优先ViewModel-first