【问题标题】:Prism 7.1 : IContainerProvider & IContainerRegistry棱镜 7.1:IContainerProvider 和 IContainerRegistry
【发布时间】:2020-12-06 22:18:22
【问题描述】:

这里是新开发人员,正在开发我的第二个应用程序,第一个使用 Prism 7.1。

我希望在正确访问在 Shell.xaml.cs 中注册的 ViewModel 方面获得一些帮助。

这是我正在使用的:

App.xaml.cs

public partial class App
{
  protected override Window CreateShell()
  {
    return Container.Resolve<Shell>();
  }
  protected override void RegisterTypes(IContanerRegistry containerRegistry)
  {
    containerRegistry.Register<ShellViewModel>();
  }
}

Shell.xaml.cs

public partial class Shell : MetroWindow
{
    public Shell()
    {
        InitializeComponent();
    }
 }

通过执行以下操作,我可以正常访问 ViewModel 的属性:

var shellVM_Instance = containerProvider.Resolve<ShellViewModel>();
shellVM_Instance.IsBusy = false;

代码会编译,但不会运行。当我运行代码时,它告诉我,上述 var shellVM_Instance 中的 ShellViewModel 正在引用 ShellViewModel 类型的空对象。这让我认为我没有正确地向 IContainerRegistry 注册 ViewModel。

谁能提供帮助?

我想避免使用 Bootstrapper 类,并利用 Prism 7.1 提供的功能 (Brian's Release Notes)

感谢您在此提供的任何指导,感谢您在我努力思考 Prism 及其真正潜力时的耐心等待。

编辑:

我看到 IContainerRegistry 有一个 RegisterInstance 方法..

void RegisterInstance(Type type, object instance);

我终其一生都无法弄清楚语法。我的尝试:

protected override void RegisterTypes(IContainerRegistry containerRegistry)
    {
        ShellViewModel shell_VM = new ShellViewModel();
        containerRegistry.RegisterInstance<ShellViewModel, shell_VM>();
    }

谢谢!

-克里斯

【问题讨论】:

  • @bakunet 谢谢。我将看看是否可以在我的应用程序中实现类似的功能。
  • 不客气。我使用 Autofac IoC,并将 Prism 仅用于 EventAggregator,但在此链接下,您可以找到如何将其用于 Prism 的不错示例。

标签: c# wpf instance unity-container prism


【解决方案1】:

IContainerRegistryIContainerRegistryExtensions

所以你可以做任何一个

containerRegistry.RegisterInstance( typeof( ShellViewModel ), shell_VM );

或一般使用扩展方法

containerRegistry.RegisterInstance<ShellViewModel>( shell_VM );

最好注册为单例,以防万一您有任何依赖项(否则您必须自己解决)

containerRegistry.RegisterSingleton<ShellViewModel>();

话虽如此,你从一开始就做错了。很少有视图模型是单例的。而是让您的视图模型通过第三方单例(EventAggregator 或您自己的服务之一)进行通信。对于您的情况,我建议如下:

public interface IApplicationBusyIndicator : INotifyPropertyChanged
{
    bool IsBusy { get; set; }
}

然后让 shell 视图模型监视 IsBusy 的更改并激活或停用您的等待覆盖,而其他视图模型或服务在它们执行操作时设置 IsBusy。当然,如果您碰巧有多个参与者使应用程序忙碌并且这些操作重叠...

public interface IApplicationBusySetter
{
    IDisposable RequestBusy();
}

然后显示等待屏幕,直到所有请求都处理完毕。

【讨论】:

  • 谢谢你,@Haukinger。我不知道这两个接口的文档。是的,我明白你为什么会说我做的事情完全错了。我目前正在使用 IEventAggregator 并在他们的视图中正确注册 ViewModel。我认为我出错的地方是将我的 ViewModels/Models 链接到同一个 IEventAggregator,因为我的两个模型引用了同一个 ViewModel 的不同实例。我将返回并确保他们使用相同的 IEventAggregator。再次感谢您!
  • 链接已失效。
猜你喜欢
  • 1970-01-01
  • 2020-08-08
  • 1970-01-01
  • 2012-01-04
  • 2018-10-25
  • 1970-01-01
  • 1970-01-01
  • 2019-09-22
  • 1970-01-01
相关资源
最近更新 更多