public IEnumerable<ISourcedEventHandler> GetEventHandlersFromAggregateRoot(IEventSource eventSource)
{
Contract.Requires<ArgumentNullException>(eventSource != null, "The eventSource cannot be null.");
var targetType = eventSource.GetType();
var handlers = new List<ISourcedEventHandler>();
foreach (var method in targetType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static))
{
EventHandlerAttribute attribute;
if (IsMarkedAsEventHandler(method, out attribute))
{
if (method.IsStatic) // Handlers are never static. Since they need to update the internal state of an eventsource.
{
var message = String.Format("The method {0}.{1} could not be mapped as an event handler, since it is static.", method.DeclaringType.Name, method.Name);
throw new InvalidEventHandlerMappingException(message);
}
if (NumberOfParameters(method) != 1) // The method should only have one parameter.
{
var message = String.Format("The method {0}.{1} could not be mapped as an event handler, since it has {2} parameters where 1 is required.", method.DeclaringType.Name, method.Name, NumberOfParameters(method));
throw new InvalidEventHandlerMappingException(message);
}
if (!typeof(IEvent).IsAssignableFrom(FirstParameterType(method))) // The parameter should be an IEvent.
{
var message = String.Format("The method {0}.{1} could not be mapped as an event handler, since it the first parameter is not an event type.", method.DeclaringType.Name, method.Name);
throw new InvalidEventHandlerMappingException(message);
}
var handler = CreateHandlerForMethod(eventSource, method, attribute);
handlers.Add(handler);
}
}
return handlers;
}