Skip to content

Instantly share code, notes, and snippets.

@typesafe
Created May 6, 2016 08:41
Show Gist options
  • Save typesafe/290af8146361f52de2fc5fe51cd83f6d to your computer and use it in GitHub Desktop.
Save typesafe/290af8146361f52de2fc5fe51cd83f6d to your computer and use it in GitHub Desktop.
DomainEvents
///<summary>
/// Provides methods for raising domaing events and registering their handlers.
///</summary>
public static class DomainEvents
{
[ThreadStatic]
private static List<Delegate> actions;
/// <summary>
/// Gets or sets the service provider used to resolve event handlers.
/// </summary>
public static IServiceProvider ServiceProvider { get; set; }
/// <summary>
/// Associates a callback with a domain event.
/// </summary>
/// <typeparam name="T">The type of event the action should be triggered for.</typeparam>
/// <param name="callback">The action to call when the specified event is raised.</param>
public static ActionRegistration Register<T>(Action<T> callback) where T : IDomainEvent
{
if (actions == null) actions = new List<Delegate>();
actions.Add(callback);
return new ActionRegistration(actions, callback);
}
public static ActionRegistration Register<THandler, TEvent>(THandler handler)
where TEvent : IDomainEvent
where THandler : IDomainEventHandler<TEvent>
{
return Register<TEvent>(handler.Handle);
}
/// <summary>
/// Clear all previously registere call back actions.
/// </summary>
public static void ClearCallbacks()
{
actions = null;
}
/// <summary>
/// Raises a domain event.
/// </summary>
/// <typeparam name="T">The type of event to raise.</typeparam>
/// <param name="args">The domain event to raise.</param>
public static void Raise<T>(T args) where T : IDomainEvent
{
if (ServiceProvider != null)
foreach (var handler in ServiceProvider.GetServices<IDomainEventHandler<T>>())
handler.Handle(args);
if (actions != null)
foreach (var action in actions)
if (action is Action<T>) ((Action<T>)action)(args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment