Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@abdullin
Created June 26, 2011 08:59
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abdullin/1047419 to your computer and use it in GitHub Desktop.
Save abdullin/1047419 to your computer and use it in GitHub Desktop.
Static helper class for invoking handling methods on AR and AR state.
// snippet is for http://abdullin.com/journal/2011/6/26/event-sourcing-a-la-lokad.html
// simple helper, that looks up and calls the proper overload of
// When(SpecificEventType event). Reflection information is cached statically
// once per type.
public static class RedirectToWhen
{
static class Cache<T>
{
public static readonly IDictionary<Type, MethodInfo> Dict = typeof(T)
.GetMethods()
.Where(m => m.Name == "When")
.Where(m => m.GetParameters().Length == 1)
.ToDictionary(m => m.GetParameters().First().ParameterType, m => m);
}
public static void InvokeEvent<T>(T instance, IEvent command)
{
MethodInfo info;
var type = command.GetType();
if (!Cache<T>.Dict.TryGetValue(type, out info))
{
var s = string.Format("Failed to locate {0}.When({1})", typeof(T).Name, type.Name);
throw new InvalidOperationException(s);
}
info.Invoke(instance, new[] { command });
}
public static void InvokeCommand<T>(T instance, ICommand command)
{
MethodInfo info;
var type = command.GetType();
if (!Cache<T>.Dict.TryGetValue(type, out info))
{
var s = string.Format("Failed to locate {0}.When({1})", typeof(T).Name, type.Name);
throw new InvalidOperationException(s);
}
info.Invoke(instance, new[] { command });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment