Skip to content

Instantly share code, notes, and snippets.

@agross
Created October 16, 2011 15:29
Show Gist options
  • Save agross/1291041 to your computer and use it in GitHub Desktop.
Save agross/1291041 to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using EasyNetQ;
using StructureMap;
using StructureMap.Query;
namespace Infrastructure
{
public static class MessageHandlers
{
public static void Load(IBus bus)
{
var handlers = ObjectFactory
.Model
.AllInstances
.Where(x => x.PluginType.IsGenericType)
.Where(x => x.PluginType.GetGenericTypeDefinition() == typeof(IHandleMessages<>))
.ToArray();
foreach (var theHandler in handlers)
{
var subscribeMethod = bus.GetType().GetMethod("Subscribe");
var messageType = theHandler.PluginType.GetGenericArguments().First();
var subscriber = subscribeMethod.MakeGenericMethod(messageType);
var handlerType = theHandler.PluginType;
Action<object> invoker = o =>
{
var allHandlers = ObjectFactory.Container.GetAllInstances(handlerType);
var handlerMethod = handlerType.GetMethod("Handle", new[] { messageType });
foreach(var h in allHandlers)
{
handlerMethod.Invoke(h, new[] { o });
}
};
subscriber.Invoke(bus, new object[] { String.Empty, invoker });
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment