使用Messenger
class 的正确方法是什么?我知道它可以用于 ViewModels/Views 通信,但是将它用于技术/业务服务层是一种好方法吗?
例如,日志/导航服务在构造函数中注册一些消息,并知道这些消息何时出现在应用程序中。发送者(ViewModel ou Service)不引用服务接口,只引用messenger发送消息。这是一个示例服务:
using System;
using System.Windows;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using App.Service.Interfaces;
using GalaSoft.MvvmLight.Messaging;
namespace App.Service
{
public class NavigationService : INavigationService
{
private PhoneApplicationFrame _mainFrame;
public event NavigatingCancelEventHandler Navigating;
public NavigationService()
{
Messenger.Default.Register<NotificationMessage<Uri>>(this, m => { this.NavigateTo(m.Content); });
}
public void NavigateTo(Uri pageUri)
{
if (EnsureMainFrame())
{
_mainFrame.Navigate(pageUri);
}
}
public void GoBack()
{
if (EnsureMainFrame()
&& _mainFrame.CanGoBack)
{
_mainFrame.GoBack();
}
}
private bool EnsureMainFrame()
{
if (_mainFrame != null)
{
return true;
}
_mainFrame = Application.Current.RootVisual as PhoneApplicationFrame;
if (_mainFrame != null)
{
// Could be null if the app runs inside a design tool
_mainFrame.Navigating += (s, e) =>
{
if (Navigating != null)
{
Navigating(s, e);
}
};
return true;
}
return false;
}
}
}