I have the following base interface
public interface IHandler{
void Handle(IMessage message);
}
and an generic interface inheriting the base interface
public interface IHandler<TMessage> : IHandler where TMessage : IMessage{
void Handle(TMessage message);
}
My classes can implement the interface IHandler<TMessage> mutiple times. IMessage is an base interface for messages and isn´t relevant here. Currently i´m implementing the interfaces as follows.
public class ExampleHandler : IHandler<ExampleMessage>, IHandler<OtherExampleMessag>{
void IHandler.Handle(IMessage message){
ExampleMessage example = message as ExampleMessage;
if (example != null) {
Handle(example);
}
else {
OtherExampleMessage otherExample = message as OtherExampleMessage;
if (otherExample != null) {
Handle(otherExample);
}
}
public void Handle(ExampleMessage) {
//handle message;
}
public void Handle(OtherExampleMessage) {
//handle message;
}
}
What bothers me is the way i have to implement the Handle(IMessage) method, cause in my opinion its many redundant code, and i have to extend the method each time when i implement a new IHandler<TMessage> interface on my class.
What i´m looking for is a more generic way to implement the Handle(IMessage) method (maybe in a base class for Handlers), but i´m currently stuck how to do that.
You can use the new
dynamickeyword to move the overload resolution to the DLR:Please note that this will fail at runtime with a
RuntimeBinderExceptionif the message passed in is not valid for your class.To avoid this exception you can add a Handler for all unknown message types:
To implement
IHandler.Handlein a base class, you need to do a little bit more work:Your specific handler would than look like this:
This code now works like this:
BaseHandler.Handle<TMessage>method with the real message type, i.e.TMessagewill not beIMessagebut the concrete message class likeExampleMessage.HandleUnknownMessageto handle the unknown message type.Handlemethod on the specific message handler, effectifly delegating the call to the concrete Handler implementation.