Last active
February 21, 2018 18:45
-
-
Save pedrohugorm/66f691d8cc9aa490032b6a596023839e to your computer and use it in GitHub Desktop.
One Simple Domain Event Publisher
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
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