I'm building a simple "bus" as a proof of concept. I do not need anything complicated but am wondering how best to optimise the following piece of code. I'm using Autofac as a container to resolve commands as open generics but actually executing the commands is currently being done via reflection as the incoming command cannot be cast to a concrete type in the code. See code - marked up with // BEGIN // END - this is currently being done with reflection. Is there a way to do this without using reflection?
// IoC wrapper
static class IoC {
public static object Resolve(Type t) {
// container gubbins - not relevant to rest of code.
}
}
// Handler interface
interface IHandles<T> {
void Handle(T command);
}
// Command interface
interface ICommand {
}
// Bus interface
interface IBus {
void Publish(ICommand cmd);
}
// Handler implementation
class ConcreteHandlerImpl : IHandles<HelloCommand> {
public void Handle(HelloCommand cmd) {
Console.WriteLine("Hello Command executed");
}
}
// Bus implementation
class BusImpl : IBus {
public void Publish(ICommand cmd) {
var cmdType = cmd.GetType();
var handler = IoC.Resolve(typeof(IHandles<>).MakeGenericType(cmdType));
// BEGIN SLOW
var method = handler.GetType().GetMethod("Handle", new [] { cmdType });
method.Invoke(handler, new[] { cmd });
// END SLOW
}
}