我主要在此MSDN article之后得到了一个应用程序。
这是我的引导程序类:
internal class Bootstrapper : UnityBootstrapper
{
// Wire up the dependencies using Unity container
protected override void ConfigureContainer()
{
base.ConfigureContainer();
// Register the connection manager
Container.RegisterType<IConnectionManager, ConnectionManager>(new ContainerControlledLifetimeManager());
}
// Return an instance of the main window
protected override DependencyObject CreateShell()
{
return ServiceLocator.Current.GetInstance<Shell>();
}
// For WPF, initialising shell is simply setting the data context and showing the main window
protected override void InitializeShell()
{
base.InitializeShell();
Application.Current.MainWindow = (Window)this.Shell;
Application.Current.MainWindow.DataContext =
ServiceLocator.Current.GetInstance<MainViewModel>();
Application.Current.MainWindow.Show();
}
}
代码中的连接管理器已向ContainerControlledLifetimeManager
注册,这意味着它将被视为singlton。
现在我的连接管理器正在实现IDisposable
,我想知道处置容器的常规方法,以便使其处置所有相关的ContainerControlledLifetimeManager
-ed对象。
我从重写应用程序的OnExit
开始,但是我发现UnitBootstrapper
没有处理方法。我可以手动编写所有代码以将容器放置在出口,但是我想必须有一种正规的方法来进行这种通常的操作。
此问题基于旧式(Prism 6)Unity Bootstrapper。此答案与Prism 7 Unity容器兼容。
IUnityContainer
对象可以使用Unity扩展方法IContainerProvider
从棱镜GetContainer()
中检索。 IUnityContainer
可以从继承自OnExit
的Application
的PrismApplication
替代中处理:
protected override void OnExit(ExitEventArgs e)
{
base.OnExit(e);
Container.GetContainer().Dispose(); // must be called to dispose singletons
}