Created
January 11, 2020 08:18
-
-
Save dmorosinotto/0936c916ece94d39f319641280112cac to your computer and use it in GitHub Desktop.
C# generic handler discovery and registration/dispatch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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