Here is my code. I’m new to generics so just wondering if there is a better way of doing what I have done.
public interface IMessageHandler<T> where T : IMessage
{
void Handle(T message);
}
public class MessageANotificationHandler : IMessageHandler<MessageA>
{
public void Handle(MessageA message)
{
// do something;
}
}
Now I want my application to receive messages which all implement IMessage but figure out automatically which handler to use for a particular message. I have done the following but have a feeling there has to a better way
public class MessageHandlerFactory
{
public Type GetMessageHandlerType(IMessage message)
{
if (message.GetType() == typeof(MessageA))
return typeof(MessageANotificationHandler);
return null;
}
}
Then in my application, I use reflection to create an instance of the type returned by the factory and invoke the Handle method.
Please help if you know any way of making this code better.
Thanks
I would remove the factory and the
IMessageHandlerinterface.. they aren’t needed.I would add the
Handlemethod to theIMessageinterface, that way instead of this:You can simply have..