Skip to content

Instantly share code, notes, and snippets.

@skyline75489
Last active May 10, 2017 01:55
Show Gist options
  • Save skyline75489/2e9bc1473f8031cbeb4f1a8ad669a259 to your computer and use it in GitHub Desktop.
Save skyline75489/2e9bc1473f8031cbeb4f1a8ad669a259 to your computer and use it in GitHub Desktop.
MvvmLight Messenger Send Derived Class Type
namespace My.Util.Messaging
{
using System;
using System.Collections.Concurrent;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using GalaSoft.MvvmLight.Messaging;
/// <summary>
/// NotifyHelper is a util class for dispatching message
/// </summary>
/// <remarks>
/// Here in this class we simply assume that all of the Types are already loaded in the assembly level.
/// </remarks>
public class NotifyHelper
{
private static readonly Lazy<MethodInfo> SendGenericMethod =
new Lazy<MethodInfo>(
() =>
Messenger.Default.GetType()
.GetMethods()
.FirstOrDefault(x => x.Name == nameof(Messenger.Default.Send) && x.IsGenericMethod));
private static readonly ConcurrentDictionary<Type, MethodInfo> MethodMap =
new ConcurrentDictionary<Type, MethodInfo>();
/// <summary>
/// Use MvvmLight Messenger to send specific type of message object.
/// </summary>
/// <remarks>
/// This method takes object as parameter and uses reflection to get the specific type and send it.
/// To boost performance, a ConcurrentDictionary is used for Type->Method mapping.
/// </remarks>
/// <param name="msg"></param>
public static void NotifySpecificType(object msg)
{
var type = msg.GetType();
MethodInfo method;
if (MethodMap.ContainsKey(type))
{
method = MethodMap[type];
}
else
{
var genericMethod = SendGenericMethod.Value;
Debug.Assert(genericMethod != null);
method = genericMethod.MakeGenericMethod(type);
MethodMap[type] = method;
}
method.Invoke(Messenger.Default, new[] { msg });
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment