我试图找到一种简单的方法来解决我的处理程序。解决方案是"处理不同类型的消息"。但是我找到的每个解决方案都是这样的想法,我坚持解决处理程序,因为我的处理程序有一个构造函数,该构造函数与其他接口有一些依赖关系。
例如,如果我遵循上述想法,我的OrderMessageHandler
是
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;
}
}
但是,IInterface
还有其他依赖项,我不能简单地解决这个问题。 不知道有没有人比这门课更好的主意?
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.
}
}
}
遵循显式依赖原则,您可以确保在何处注入所有必要的依赖关系。
public class MessageProcessor {
private List<IMessageHandler> handlers;
public MessageProcessor(IEnumerable<IMessageHandler> handlers) {
this.handlers = new List<IMessageHandler>(handlers);
//removed
//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.
}
}
}
如果使用 DI 容器,请确保注册所有相关方
伪代码:
container.Register<IInterface, Implementation>();
container.Register<IMessageHandler, SomeOtherMessageHandler>();
container.Register<IMessageHandler, OrderMessageHandler>();
container.Register<MessageProcessor>();
这样,容器就知道如何在解析所需类型时构建对象图
MessageProcessor processor = container.Resolve<MessageProcessor>();
processor.ProcessMessage(...);
//...
如果使用纯 DI,这仍然允许在需要时正确创建和注入所涉及的所有类型。
IInterface dependency = new Implementation();
List<IMessageHandler> handlers = new List<IMessageHandler>();
handlers.Add(new SomeOtherMessageHandler());
handlers.Add(new OrderMessageHandler(dependency));
MessageProcessor processor = new MessageProcessor(handlers);
processor.ProcessMessage(...);
//...