Bootstrapper負責引導應用程序,用於配置 IoC 容器,創建根 ViewModel 的新實例,並使用顯示WindowManager出來。它還提供了各種其他功能,如下所述。
引導程序有兩種風格:BootstrapperBase
示例引導程序,使用 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容器的引導程序。這些都是經過單元測試的,但未經實戰測試:隨意自定義它們。
請注意,Stylet nuget 包/ dll 不包含這些,因為它會添加不必要的依賴項。同樣,我不會發布特定於 IoC 容器的包,因為這是浪費精力。
將所需的引導程序從上面的鏈接復制到項目中的某個位置。然后對它進行子類化,就像您通常對 上文所述進行子類化一樣。然后將子類添加到 App.xaml.cs,如快速入門中所述,例如Bootstrapper<TRootViewModel>
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 本身就是一個資源字典。如果您需要將自己的資源字典添加到 App.xaml,則必須將 s:ApplicationLoader 嵌套在資源字典中作為合並詞典,如下所示:
<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>