Search code examples
mvvmmvvm-lightseparation-of-concerns

Where is good place to register Messenger responsible for showing Windows to ensure MVVM pattern Separation of Concerns and Testability not violated?


Scenario:

MainWindow has a Menu About which relates to AboutWindow.

About Meny is triggered by command:

<MenuItem Header="_About" Command="{Binding OpenAbout}"/>

OpenAbout is property like that:

  private RelayCommand _openAbout;
        public RelayCommand OpenAbout
        {
            get
            {
                return _openAbout ?? (_openAbout = new RelayCommand(() => Messenger.Default.Send(new NotificationMessage("ShowAboutView"))));
            }
        }

Notification message is registered in App.cs class as follows:

 static App()
        {
            DispatcherHelper.Initialize();
        }

        public App()
        {
            RegisterMessenger();
        }

        public void RegisterMessenger()
        {
            Messenger.Default.Register<NotificationMessage>(this, ProcessShowAboutView);          
        }

        private void ProcessShowAboutView(NotificationMessage message)
        {
            AboutWindow view = new AboutWindow();
            view.Show();
        }

I analysed another questions like that:

How to open a new window using MVVM Light Toolkit

WPF MVVM - How to Show a view from MainWindowViewModel upon Clicking on button

I like Messenger functionality but however I am not sure If above solution is a good one. I would be thankful for any advise!

As depicted above, Registering messages is done in App Config. I consider it not be a good place therefore I need to know what place would be better. Another place to consider would be Locator


Solution

  • I personaly would register the messages in App.xaml.cs in the OnStartup method (WPF) and in the set up method of the unit test (dont forget to unregister everything in the tear down method).