Skip to content

Instantly share code, notes, and snippets.

@follesoe
Created February 13, 2012 10:34
Show Gist options
  • Save follesoe/1815856 to your computer and use it in GitHub Desktop.
Save follesoe/1815856 to your computer and use it in GitHub Desktop.
class Program
{
static void Main(string[] args)
{
var handlers = new MyHandlerList();
handlers.Add(new ConcreteHandler());
var myHandler = handlers.Get<Message>();
}
private class MyHandlerList
{
private readonly Dictionary<Type, object> _handlers = new Dictionary<Type, object>();
public void Add<T>(IHandler<T> handler) where T : IMessage
{
_handlers.Add(typeof(T), handler);
}
public IHandler<T> Get<T>() where T : IMessage
{
if (_handlers.ContainsKey(typeof(T)))
return _handlers[typeof(T)] as IHandler<T>;
throw new Exception("Not found");
}
}
private interface IHandler<in TMessage>
where TMessage : IMessage
{
void Handle(TMessage message);
}
private interface IMessage
{
}
private class Message : IMessage
{
}
class ConcreteHandler : IHandler<Message>
{
private IMessage Message { get; set; }
public void Handle(Message message)
{
Message = message;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment