0
votes

the reason of my issue is: I'm tyring to avoid the EventAggregator-Pattern, because I think it makes code hard to understand and to debug.

Instead of using EventAggregator I tried to create a ShellViewModel and inject two ViewModels which should be wired to together for some reason:

public ShellViewModel(DocumentViewModel documentViewModel, ToolsViewModel toolsViewModel)
    {
      ...
    }

The problem I'm facing now is, that the documentViewModel and the toolsViewModel is created twice:

in my Bootstrapper:

protected override DependencyObject CreateShell()
    {
        return Container.Resolve<Shell>(); //this implicitly calls the ctors of my viewmodels
    }

and in my module:

public void Initialize()
    {
        //This calls create the ViewModels again
        regionViewRegistry.RegisterViewWithRegion("ToolRegion", typeof(Views.ToolsView));
        regionViewRegistry.RegisterViewWithRegion("MainRegion", typeof(Views.DocumentView));
    }

How can I avoid, that the constructors are called twice? If that is the wrong idea, how do I connect events of viewmodels in the same module?

Edit (Solved):

public ShellViewModel(IDocumentViewModel documentViewModel, IToolsViewModel toolsViewModel)
    {
      ...
    }

and

protected override void ConfigureContainer()
 {
   base.ConfigureContainer();
   RegisterTypeIfMissing(typeof (IToolsViewModel), typeof (ToolsViewModel), true);
   RegisterTypeIfMissing(typeof(IDocumentViewModel), typeof(DocumentViewModel), true);
 }

did the trick. It's neccessary to create an interface of the viewmodels and register the interface. Otherwise Unity will always create a new instance.

1

1 Answers

0
votes
public ShellViewModel(IDocumentViewModel documentViewModel, IToolsViewModel toolsViewModel)
    {
      ...
    }

and

protected override void ConfigureContainer()
 {
   base.ConfigureContainer();
   RegisterTypeIfMissing(typeof (IToolsViewModel), typeof (ToolsViewModel), true);
   RegisterTypeIfMissing(typeof(IDocumentViewModel), typeof(DocumentViewModel), true);
 }

did the trick. It's neccessary to create an interface of the viewmodels and register the interface. Otherwise Unity will always create a new instance.