将调度程序注入视图模型 - 重构 Unity - 属性注入

本文关键字:注入 重构 Unity 属性 模型 调度程序 视图 | 更新日期: 2023-09-27 18:36:49

我正在尝试将 ShellPage 的调度程序注入我的 Unity 和 Prism 的 ViewModel 中。由于调度程序在创建 shell 后可用,因此我无法及时注册调度程序。
第一步:

 protected override Task OnInitializeAsync(IActivatedEventArgs args)
        {
            [...]
            Container.RegisterInstance<IResourceLoader>(resourceLoader);

其次,将执行 CreateShell 方法。

protected override UIElement CreateShell(Frame rootFrame)
        {
            var shell = Container.Resolve<ShellPage>();
            Container.RegisterType<MyViewModel>(new InjectionProperty(nameof(MyViewModel.Dispatcher), shell.Dispatcher));

虽然我将调度程序注入到我的视图模型中,但调度程序是空的。也许我需要像在 MEF 中重新组合这样的东西?如何实现属性注入到我的视图模型中?

将调度程序注入视图模型 - 重构 Unity - 属性注入

我认为

是不可能的。不支持像 MEF 一样进行重构。

简单的方法是创建一个帮助程序来获取当前视图的调度程序并在视图模型中使用它

请看这个例子:http://mikaelkoskinen.net/post/fixing-coredispatcher-invoke-how-to-invoke-method-in-ui-thread-in-windows-8-release-preview

此示例适用于 Windows 8,但你可以将其用于 UWP 应用

就在我使用此方法时,我会对 UWP 应用进行一些小更改:

在 app.xaml 中的启动事件中.cs

我在不同的位置添加了UIDispatcher。

 if (rootFrame.Content == null)
        {
            // When the navigation stack isn't restored navigate to the first page,
            // configuring the new page by passing required information as a navigation
            // parameter
            UIDispatcher.Initialize();
            rootFrame.Navigate(typeof(MainPage), e.Arguments);
        }
        // Ensure the current window is active
        Window.Current.Activate();