Created
September 19, 2014 13:09
-
-
Save jbogard/54d6569e883f63afebc7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IDomainEventDispatcher | |
{ | |
void Dispatch(IDomainEvent domainEvent); | |
} | |
public class DomainEventDispatcher : IDomainEventDispatcher | |
{ | |
private readonly IContainer _container; | |
public DomainEventDispatcher(IContainer container) | |
{ | |
_container = container; | |
} | |
public void Dispatch(IDomainEvent domainEvent) | |
{ | |
var handlerType = typeof (IDomainEventHandler<>).MakeGenericType(domainEvent.GetType()); | |
var wrapperType = typeof (DomainEventHandler<>).MakeGenericType(domainEvent.GetType()); | |
var handlers = _container.GetAllInstances(handlerType); | |
var wrappedHandlers = handlers | |
.Cast<object>() | |
.Select(handler => (DomainEventHandler) Activator.CreateInstance(wrapperType, handler)); | |
foreach (var handler in wrappedHandlers) | |
{ | |
handler.Handle(domainEvent); | |
} | |
} | |
private abstract class DomainEventHandler | |
{ | |
public abstract void Handle(IDomainEvent domainEvent); | |
} | |
private class DomainEventHandler<T> : DomainEventHandler | |
where T : IDomainEvent | |
{ | |
private readonly IDomainEventHandler<T> _handler; | |
public DomainEventHandler(IDomainEventHandler<T> handler) | |
{ | |
_handler = handler; | |
} | |
public override void Handle(IDomainEvent domainEvent) | |
{ | |
_handler.Handle((T) domainEvent); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment