c# - Prism 7.1 : IContainerProvider & IContainerRegistry

标签 c# wpf instance unity-container prism

这里是新开发人员,正在开发我的第二个应用程序,第一个应用程序使用 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;

代码可以编译,但不会运行。当我运行代码时,它告诉我 ShellViewModel 从上面的 var shellVM_Instance 中引用了 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>();
    }

谢谢!

-克里斯

最佳答案

IContainerRegistryIContainerRegistryExtensions .

所以你可以做任何一个

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

或者一般使用扩展方法

containerRegistry.RegisterInstance<ShellViewModel>( shell_VM );

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

containerRegistry.RegisterSingleton<ShellViewModel>();

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

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

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

public interface IApplicationBusySetter
{
    IDisposable RequestBusy();
}

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

关于c# - Prism 7.1 : IContainerProvider & IContainerRegistry,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56741827/

相关文章:

c# - 删除扩展 WPF 工具包样式中的关闭按钮

c# - 如何在 WPF DataGrid 列中制作互斥复选框

wpf - 使用 WPF TextBox 模仿 VS 输出窗口的文本框的问题

ios - 生成自定义 UIView 的 UINib 实例,出现 'not key value coding-compliant' 错误

.net - 如何使用反射在 C# 文件中创建 List<T> 实例

java - 创建使用参数的可运行程序

c# - 在.net 4.5项目中使用.net 2.0 dll(vshost在调试时崩溃)

c# - 如何在 C# 中以波斯语格式打印 DateTime

c# - 向 DataGrid 添加文本框

c# - 我应该将上传的(img 文件)保存到 App_Data 吗?