I try to find a simple way to resolve my handlers. The solution is "handling different types of messages". but each solution I found such as this idea, I stuck in resolving the handler because my handler has a constructor which has some dependencies to other interfaces.
For example, if I follow the mentioned idea my OrderMessageHandler
is
public class OrderMessageHandler
{
private readonly IInterface _interface;
public OrderMessageHandler(IInterface interface) {_inteface=interface}
bool HandleMessage( IMessage msg ) {
if ( !(msg is OrderMessage)) return false;
return true;
}
}
However that IInterface
has other dependencies and I can not simply resolve that.
I wonder if anyone has a better idea than this below class?
public class MessageProcessor {
private List<IMessageHandler> handlers;
public MessageProcessor() {
handlers = new List<IMessageHandler>();
handlers.add(new SomeOtherMessageHandler());
handlers.add(new OrderMessageHandler());
}
public void ProcessMessage( IMessage msg ) {
bool messageWasHandled
foreach( IMessageHandler handler in handlers ) {
if ( handler.HandleMessage(msg) ) {
messageWasHandled = true;
break;
}
}
if ( !messageWasHandled ) {
// Do some default processing, throw error, whatever.
}
}
}