Bootstrapper引导程序
bootstrapper负责引导应用程序。它配置IoC容器,创建根ViewModel的新实例,并使用WindowManager
显示它。它还提供各种其他功能,如下所述。
bootstrapper有两种风格:BootstrapperBase<TRootViewModel>
,它需要您自己配置IoC容器,以及Bootstrapper<TRootViewModel>
(使用Stylet的内置IoC容器StyletIoC)。
使用StyletIoC的引导程序示例:
class Bootstrapper : Bootstrapper<MyRootViewModel>
{
protected override void OnStart()
{
// This is called just after the application is started, but before the IoC container is set up.
// Set up things like logging, etc
}
protected override void ConfigureIoC(IStyletIoCBuilder builder)
{
// Bind your own types. Concrete types are automatically self-bound.
builder.Bind<IMyInterface>().To<MyType>();
}
protected override void Configure()
{
// This is called after Stylet has created the IoC container, so this.Container exists, but before the
// Root ViewModel is launched.
// Configure your services, etc, in here
}
protected override void OnLaunch()
{
// This is called just after the root ViewModel has been launched
// Something like a version check that displays a dialog might be launched from here
}
protected override void OnExit(ExitEventArgs e)
{
// Called on Application.Exit
}
protected override void OnUnhandledException(DispatcherUnhandledExceptionEventArgs e)
{
// Called on Application.DispatcherUnhandledException
}
}
使用自定义IoC容器
将另一个IoC容器与Stylet一起使用很容易。我在Bootstrappers项目中包含了许多流行的IoC容器的Bootstrapper。这些都经过了单元测试,但没有经过战斗测试:请随意定制。
请注意,Stylet-nuget包/dll不包括这些,因为它会添加不必要的依赖项。类似地,我不发布IoC容器特定的包,因为这是浪费精力。
将你想要的引导程序从上面的链接复制到你的项目中。然后将其子类化,就像您通常将Bootstrapper<TRootViewModel>
子类化一样,如上所述。然后将您的子类添加到App.xaml.cs中,如快速入门中所述,例如。
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,则必须在ResourceDictionary中嵌套s:ApplicationLoader作为MergedDictionary,如下所示:
<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>