Skip to content

Instantly share code, notes, and snippets.

@pedrohugorm
Last active February 21, 2018 18:45
Show Gist options
  • Save pedrohugorm/66f691d8cc9aa490032b6a596023839e to your computer and use it in GitHub Desktop.
Save pedrohugorm/66f691d8cc9aa490032b6a596023839e to your computer and use it in GitHub Desktop.
One Simple Domain Event Publisher
using System.Collections.Generic;
using System.Linq;
namespace Core.DomainEvents
{
public interface IDomainEvent
{
}
public interface IDomainEventSubscriber<in TDomainEvent> where TDomainEvent : IDomainEvent
{
void Handle(TDomainEvent domainEvent);
}
public class DomainEventPublisher
{
private readonly HashSet<object> subscribers = new HashSet<object>();
private DomainEventPublisher()
{
}
public void Publish<TDomainEvent>(TDomainEvent domainEvent) where TDomainEvent : IDomainEvent
{
IEnumerable<object> validSubscribers = this.subscribers.Where(r => r is IDomainEventSubscriber<TDomainEvent>);
foreach (IDomainEventSubscriber<TDomainEvent> subscriber in validSubscribers)
{
subscriber.Handle(domainEvent);
}
}
public void Register<TDomainEvent>(IDomainEventSubscriber<TDomainEvent> subscriber) where TDomainEvent : IDomainEvent
{
this.subscribers.Add(subscriber);
}
private static DomainEventPublisher domainEventPublisherInstance;
public static DomainEventPublisher Instance
{
get
{
if (domainEventPublisherInstance == null)
{
domainEventPublisherInstance = new DomainEventPublisher();
}
return domainEventPublisherInstance;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment