如何正确处理由Prism-Unity-WPF应用程序中的ContainerControlledLifetimeManager创建的依赖项

问题描述 投票:2回答:1

我主要在此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没有处理方法。我可以手动编写所有代码以将容器放置在出口,但是我想必须有一种正规的方法来进行这种通常的操作。

wpf singleton unity-container prism dispose
1个回答
0
投票

此问题基于旧式(Prism 6)Unity Bootstrapper。此答案与Prism 7 Unity容器兼容。

IUnityContainer对象可以使用Unity扩展方法IContainerProvider从棱镜GetContainer()中检索。 IUnityContainer可以从继承自OnExitApplicationPrismApplication替代中处理:

protected override void OnExit(ExitEventArgs e)
{
    base.OnExit(e);
    Container.GetContainer().Dispose(); // must be called to dispose singletons
}
© www.soinside.com 2019 - 2024. All rights reserved.