概念実証として単純な「バス」を構築しています。複雑なことは何も必要ありませんが、次のコードを最適化する方法を考えています。コマンドをオープン ジェネリックとして解決するためのコンテナーとして Autofac を使用していますが、実際にコマンドを実行することは現在、リフレクションを介して行われています。コードを参照 - // BEGIN // END でマークアップ - これは現在リフレクションで行われています。リフレクションを使用せずにこれを行う方法はありますか?
// 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
}
}