通过 XAML 实例化视图时 SimpleInjector.Container.Verify 中的 NullReferenceException

NullReferenceException in SimpleInjector.Container.Verify when instancing view via XAML

我仍在学习 WPF 的过程中,还决定试一试 Simple Injector。我基于 WPF integration example provided in the Simple Injector documentation 创建了一个非常简单的测试项目。我当前的代码与该示例几乎相同,或者可以说更简单,因为我还没有任何服务对象。

不同的是,我确实有一个简单的 View 和一个随附的 ViewModel,这是目前 MainWindow:

上唯一的东西
    <Window x:Class="WpfPlayground.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:WpfPlayground"
            xmlns:view="clr-namespace:WpfPlayground.View"
            mc:Ignorable="d"
            Title="MyApp" Height="450" Width="800">
        <Grid>
            <view:MyView />
        </Grid>
    </Window>

我的 MainWindowViewModel class 存在,但目前仍然是空的。它的构造函数没有参数。

这是我到目前为止的 MyView(XAML 仍然只是一个空的 <Grid />):

public partial class MyView : UserControl
{
    public MyView(MyViewModel myViewModel)
    {
        InitializeComponent();
        DataContext = myViewModel;
    }
}

这是我的 Program class:

中的 Bootstrap() 方法
        private static Container Bootstrap()
        {
            var container = new Container();

            container.Register<MainWindow>();
            container.Register<MainWindowViewModel>();
            container.Register<MyView>();
            container.Register<MyViewModel>();

            container.Verify();

            return container;
        }

现在,当调用 InitializeComponent() ("Object reference not set to an instance of an object") 时,我在 MainWindow 构造函数中得到一个 NullReferenceException。调用堆栈指向 Program.Bootstrap() 中对 container.Verify() 的调用(见上文)。 MyViewModelMyView 的构造函数都未达到。

如果我猜的话,我会说应用程序没有通过 Container 来获取 MyView 的实例。我进行此实验的原因之一实际上是因为我有兴趣了解 Simple Injector 如何完成此操作,因为文档似乎暗示这会以某种方式自动发生。文档中可能缺少一个步骤吗?注册某种拦截器的东西?毕竟,这可能不是将 Simple Injector 与 WPF/XAML 一起使用的正确方法吗?希望我不必在代码中创建控件?

If I were to take a guess I'd say that the application is not going through the Container to get the instance of MyView

是的,SimpleInjector 不能 能够解析您在 XAML 标记中内联定义的视图,就像这样。

当在运行时调用 InitializeComponent() 方法时,内置解析器会尝试创建您在 XAML 标记中定义的视图的实例,而无需了解或参考任何容器。

因此,当您尝试解析 MainWindow 的实例时,您的代码会失败,因为在其构造函数中调用 InitializeComponent() 会引发异常。

您引用的文档中的示例未定义任何内联视图。这仅适用于具有无参数构造函数的视图。