Unity container PRISM、Unity、EventAggregator、ShellViewModel:构造函数被调用两次
我的问题的原因是: 我一直在避免使用EventAggregator模式,因为我认为这会使代码难以理解和调试 我没有使用EventAggregator,而是尝试创建一个ShellViewModel并注入两个ViewModel,出于某种原因,这两个ViewModel应该连接在一起:Unity container PRISM、Unity、EventAggregator、ShellViewModel:构造函数被调用两次,unity-container,viewmodel,prism,Unity Container,Viewmodel,Prism,我的问题的原因是: 我一直在避免使用EventAggregator模式,因为我认为这会使代码难以理解和调试 我没有使用EventAggregator,而是尝试创建一个ShellViewModel并注入两个ViewModel,出于某种原因,这两个ViewModel应该连接在一起: public ShellViewModel(DocumentViewModel documentViewModel, ToolsViewModel toolsViewModel) { ...
public ShellViewModel(DocumentViewModel documentViewModel, ToolsViewModel toolsViewModel)
{
...
}
我现在面临的问题是,documentViewModel和toolsViewModel创建了两次:
在我的引导程序中:
protected override DependencyObject CreateShell()
{
return Container.Resolve<Shell>(); //this implicitly calls the ctors of my viewmodels
}
如何避免构造函数被调用两次?
如果这是错误的想法,如何在同一模块中连接viewmodels的事件
编辑已解决的问题:
及
成功了。有必要创建viewmodels的接口并注册该接口。否则Unity将始终创建一个新实例
及
成功了。有必要创建viewmodels的接口并注册该接口。否则Unity将始终创建一个新实例。不太可能。您可以注册一个类,而不是一个接口。这两个版本之间的关键区别在于,适用于您的版本是RegisterTypeIfMissing,而不仅仅是RegisterType。如果您只需要一个特定类的单个实例,那么还可以使用受控生存期对其进行注册,如下所示:this.Container.RegisterTypenew Container controlled LifetimeManager;我试过这个.Container.RegisterTypenew ContainerControlled LifetimeManager;起初没有成功。构造函数仍被调用了两次。请尝试在引导程序中添加this.Container.Resolve;除了RegisterType之外。当我想要将一个类的单个实例导入多个不同的类时,我使用这种模式。
public void Initialize()
{
//This calls create the ViewModels again
regionViewRegistry.RegisterViewWithRegion("ToolRegion", typeof(Views.ToolsView));
regionViewRegistry.RegisterViewWithRegion("MainRegion", typeof(Views.DocumentView));
}
public ShellViewModel(IDocumentViewModel documentViewModel, IToolsViewModel toolsViewModel)
{
...
}
protected override void ConfigureContainer()
{
base.ConfigureContainer();
RegisterTypeIfMissing(typeof (IToolsViewModel), typeof (ToolsViewModel), true);
RegisterTypeIfMissing(typeof(IDocumentViewModel), typeof(DocumentViewModel), true);
}
public ShellViewModel(IDocumentViewModel documentViewModel, IToolsViewModel toolsViewModel)
{
...
}
protected override void ConfigureContainer()
{
base.ConfigureContainer();
RegisterTypeIfMissing(typeof (IToolsViewModel), typeof (ToolsViewModel), true);
RegisterTypeIfMissing(typeof(IDocumentViewModel), typeof(DocumentViewModel), true);
}