I'm working on a system for handling events:
public interface IEvent { ..}
public class CreateUserEvent : IEvent {...}
public class ChangeUserNameEvent : IEvent {...}
Each event has a specific handler
public interface IEventHandler<T> where T : IEvent { Handle(T @event); }
public class CreateUserEventHandler : IEventHandler<CreateUserEvent> { ... }
public class ChangeUserNameEventHandler : IEventHandler<ChangeUserNameEvent> {...}
So far everything is pretty straight forward. However, I would like to create class that uses the right event handler, for the right event.
So far I've come up with the following method:
Dictionary<Type, object> EventHandlers; // stores all registered event handlers
// Note that at compile time I do not exactly know the specialization of IEvent
// so I cannot give HandleEvent a generic type parameter :(
void HandleEvent(IEvent @event)
{
// inspect the type of the event handler at runtime
// the event also needs to be dynamic. Even though we know its a
// specialization of IEvent that is compatible with
// the handlers .Handle method
var handler = EventHandlers[@event.GetType()] as dynamic;
hanler.Handle(@event as dynamic);
}
This solution works, but I have to use two dynamic types, this worries me. I think I might be making a wrong design decision, but I can think of no other architecture/pattern to get rid of these dynamics.
So my question boils down to this: How can I select and use the right implemenation of an interface with a generic with minimal run-time introspection?
Note I prefer a solution where IEvent and IEventHandler implementations are completely unaware of this process