using System.Collections.Generic;
using System.Reflection.Emit;
using System.Threading.Tasks;
using DeepThoughts.MessageHandlers;
using DeepThoughts.Messages;
public static class MessageDispatcher
private static Dictionary<Type, MessageHandler> _handlers;
public static void Dispatch(IMessage message)
_handlers[message.GetType()].HandleMessage(message);
public static void Initialize()
_handlers = new Dictionary<Type, MessageHandler>();
var types = Assembly.GetCallingAssembly().GetTypes();
var messages = types.Where(t => t.Namespace == "DeepThoughts.Messages" && !t.IsAbstract);
var handlers = types.Where(t => t.Namespace == "DeepThoughts.MessageHandlers" && !t.IsAbstract);
foreach (var msg in messages)
var m = Activator.CreateInstance(msg);
foreach (var handler in handlers)
if (handler.BaseType != null && handler.BaseType.GetGenericArguments()[0] == m.GetType())
var h = (MessageHandler)Activator.CreateInstance(handler);
_handlers.Add(m.GetType(), h);
foreach (var handler in _handlers.Values)
var methods = obj.GetType().GetMethods(BindingFlags.NonPublic|BindingFlags.Instance);
foreach (var method in methods)
var attributes = method.GetCustomAttributes(typeof(InitializerAttribute), false);
foreach (var a in attributes)
if (a.GetType() == typeof(InitializerAttribute))
method.Invoke(obj, null);