使用 Simple Injector 将所有 views/viewmodels 的实例加倍

Doubled instances of all views/viewmodels with Simple Injector

使用 Simple Injector 尝试 MVVM,我遵循了这个指南:https://simpleinjector.readthedocs.io/en/latest/wpfintegration.html

即使最简单的示例只有 MainWindow.xaml + MainWindowViewModel,它也会创建 View 和 ViewModel 的双实例(我也尝试省略容器验证)。此外,应用程序关闭后,进程仍然存在 运行.

    [STAThread]
    static void Main()
    {
        var container = new Container();
        container.Register<MainWindow>();
        container.Register<MainWindowViewModel>();

        var app = new App();
        app.InitializeComponent();

        var mainWindow = container.GetInstance<MainWindow>();
        app.Run(mainWindow);      
    }

但是我确实将 App.xaml 中的 StartupUri 替换为 Startup 方法,该方法是空的,就好像我没有这样做一样 app.InitializeComponent() 方法将不可用。

对用于 MVVM 目的的 DI 容器有什么建议吗?

正如ContainerOptions.EnableAutoVerification本身的定义

ContainerOptions.EnableAutoVerification Gets or sets a value indicating whether the container should automatically trigger verification and diagnostics of its configuration when the first service is resolved (e.g. the first call to GetInstance). The behavior is identical to calling Verify() manually. The default is true.

参考https://github.com/simpleinjector/SimpleInjector/issues/747

您看到的是 Simple Injector v5 中引入的行为和重大更改。此更改在 here and noted in the release notes of v5.

中有更详细的描述

简而言之,容器现在会在第一次解析时自动验证完整配置。在您的情况下,验证会导致创建所有 windows,而 windows 在验证后不会关闭(因为 Simple Injector 不知道它们应该被关闭)。这会导致应用程序最终保持打开状态。

您可以不使用自动验证,而是使用:

container.Options.EnableAutoVerification = false

转而从单元测试中验证容器。