Skip to content

Instantly share code, notes, and snippets.

@danbarua
Last active August 29, 2015 14:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danbarua/efcaf10f351d172e8b0e to your computer and use it in GitHub Desktop.
Save danbarua/efcaf10f351d172e8b0e to your computer and use it in GitHub Desktop.
public class CommandHandlersModule : NinjectModule
{
public override void Load()
{
this.Kernel.Bind(
x =>
x.FromAssembliesMatching("WordWatch.*")
.SelectAllClasses()
.InheritedFrom(typeof(ICommandHandler<>))
.BindAllInterfaces());
}
}
public class NInjectCommandDispatcher : ICommandDispatcher
{
private readonly IKernel kernel;
public NInjectCommandDispatcher(IKernel kernel)
{
this.kernel = kernel;
}
public void Dispatch<T>(T message)
{
this.kernel.Get<ICommandHandler<T>>().Handle(message);
}
}
public class NInjectQueryMediator : IQueryMediator
{
private static readonly IDictionary<Type, IDictionary<Type, MethodInfo>> Cache =
new ConcurrentDictionary<Type, IDictionary<Type, MethodInfo>>();
private static readonly MethodInfo InternalPreserveStackTraceMethod =
typeof(Exception).GetMethod("InternalPreserveStackTrace", BindingFlags.Instance | BindingFlags.NonPublic);
private readonly IKernel kernel;
public NInjectQueryMediator(IKernel kernel)
{
this.kernel = kernel;
}
public TResult Handle<TResult>(IQuery<TResult> query)
{
var queryType = query.GetType();
var resultType = typeof(TResult);
var handlerType = typeof(IQueryHandler<,>).MakeGenericType(queryType, resultType);
var handler = this.kernel.Get(handlerType);
return (TResult)InvokeHandle(handler, query);
}
[DebuggerNonUserCode]
private static object InvokeHandle(object instance, object message)
{
MethodInfo info;
var instanceType = instance.GetType();
IDictionary<Type, MethodInfo> lookup;
if (!Cache.TryGetValue(instanceType, out lookup))
{
lookup =
instanceType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(m => m.Name == "Handle")
.Where(m => m.GetParameters().Length == 1)
.ToDictionary(m => m.GetParameters().First().ParameterType, m => m);
Cache[instanceType] = lookup;
}
var eventType = message.GetType();
if (!lookup.TryGetValue(eventType, out info))
{
var s = string.Format("Failed to locate {0}.Handle({1})", instanceType.Name, eventType.Name);
throw new InvalidOperationException(s);
}
try
{
return info.Invoke(
instance,
new[]
{
message
});
}
catch (TargetInvocationException ex)
{
if (null != InternalPreserveStackTraceMethod) InternalPreserveStackTraceMethod.Invoke(ex.InnerException, new object[0]);
throw ex.InnerException;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment