简体   繁体   English

C#Prism:在视图实例化之前实例化模型

[英]C# Prism: Instantiate Model before View Instantiation

TL;DR Is there a way to force MEF Prism container to instantiate a class before it's instantiated by View Disovery? TL; DR是否有一种方法可以强制MEF Prism容器在通过View Disovery实例化某个类之前实例化该类? ie before regionManager.RegisterViewWithRegion 即在regionManager.RegisterViewWithRegion之前

I have a business process whereby the user logs in, and then I kick off some database reads. 我有一个业务流程,用户可以通过该流程登录,然后启动一些数据库读取操作。 The LoginEvent is registered to the EventAggregator so that other parts of the application can hear it. LoginEvent已注册到EventAggregator以便应用程序的其他部分可以听到它。 The problem is that my model MyModel is only instantiated after the dependent views have been registered which of course happens after the login event has passed and gone. 问题是我的模型MyModel仅在注册了依赖视图之后才实例化,这当然会登录事件过去并消失之后发生。 I could do this MyModel 's constructor but that feels sloppy. 我可以做这个MyModel的构造函数,但是感觉很草率。

Current Process 当前过程

1. User logs in
2. LoginEvent is dispatched
2. View switches to MyView
3. MyModel is instantiated and listens for LoginEvent that will never be dispatched

Desired Process 所需过程

1. MyModel is instantiated and listens for LoginEvent
2. User Logs in
3. LoginEvent is dispatched
4. MyModel hears LoginEvent and kicks of data read.

Any help on this is greatly appreciated. 在此方面的任何帮助将不胜感激。

Instantiate your view ahead of time so that it is available to listen on events. 提前实例化视图,以便可以监听事件。 You can use Module concepts as described in prism docs to instantiate your view inside your module Initialize event. 您可以使用棱镜文档中描述的模块概念在模块Initialize事件中实例化视图。 This will have following sequence: 这将具有以下顺序:

  1. App starts up 应用启动
  2. Module starts up 模块启动
  3. View instantiated & registered 查看实例化并注册
  4. User Logs in 用户登录
  5. LoginEvent intercepted LoginEvent被拦截
  6. View switches 查看开关

Following example gives you some outline (hasn't been tested, but should be structurally valid): 以下示例为您提供了一些概述(尚未经过测试,但在结构上应是有效的):

public class ModuleInit : IModule
{
  .....
  CompositionContainer container;
  IRegionManager regionManager;

  [ImportingConstructor]
  public ModuleInit(CompositionContainer container, IRegionManager regionManager)
  {
      this.container = container;
      this.regionManager = regionManager;
  }

  public void Initialize()
  {
     var myView = this.container.GetExportedValue<MyView>();
     regionManager.RegisterViewWithRegion("myregion", () => myView);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM