Skip to content

Instantly share code, notes, and snippets.

@dmorosinotto
Created January 11, 2020 08:18
Show Gist options
  • Save dmorosinotto/0936c916ece94d39f319641280112cac to your computer and use it in GitHub Desktop.
Save dmorosinotto/0936c916ece94d39f319641280112cac to your computer and use it in GitHub Desktop.
C# generic handler discovery and registration/dispatch
// types
public interface IHandleForwarder
{
object ForwardToHandle(object input);
}
public abstract class AbstractMessageHandler<TIn,TOut> : IHandleForwarder
{
public abstract TOut Handle(TIn input);
object IHandleForwarder.ForwardToHandle(object input)
{
return Handle((TIn)input);
}
}
// setup
var handlers = from type in typeof(Program).Assembly.GetTypes()
where type.IsGenericType
where typeof(AbstractMessageHandler<,>).IsAssignableFrom(type.GetGenericTypeDefinition())
select type;
var handlersMap = new Dictionary<Type, Func<object, object>>();
foreach (var handler in handlers)
{
var input = handler.GetGenericArguments()[0];
var handleForwarder = (IHandleForwarder)Activator.CreateInstance(handler);
handlersMap[input] = handleForwarder.ForwardToHandle;
}
// handling a message:
var reply = handlersMap[msg.GetType()](msg);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment