Created
July 28, 2014 11:13
-
-
Save feanz/57d7bed5880b85b45825 to your computer and use it in GitHub Desktop.
Nice way to handle Domain events
http://www.udidahan.com/2009/06/14/domain-events-salvation/
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 static class DomainEvents | |
{ | |
[ThreadStatic] //so that each thread has its own callbacks | |
private static List<Delegate> actions; | |
public static IContainer Container { get; set; } //as before | |
//Registers a callback for the given domain event | |
public static void Register<T>(Action<T> callback) where T : IDomainEvent | |
{ | |
if (actions == null) | |
actions = new List<Delegate>(); | |
actions.Add(callback); | |
} | |
//Clears callbacks passed to Register on the current thread | |
public static void ClearCallbacks () | |
{ | |
actions = null; | |
} | |
//Raises the given domain event | |
public static void Raise<T>(T args) where T : IDomainEvent | |
{ | |
if (Container != null) | |
foreach(var handler in Container.ResolveAll<Handles<T>>()) | |
handler.Handle(args); | |
if (actions != null) | |
foreach (var action in actions) | |
if (action is Action<T>) | |
((Action<T>)action)(args); | |
} | |
} |
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 IDomainEvent | |
{} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment