如何以干净的方式解决处理程序

时间:2019-10-08 11:51:31

标签: c# dependency-injection dependency-resolver

我试图找到一种解决我的处理程序的简单方法。解决方案是“处理不同类型的消息”。但是我找到的每个解决方案(例如this idea)都停留在解析处理程序上,因为我的处理程序具有一个构造函数,该构造函数与其他接口具有某些依赖性。

例如,如果我遵循上述想法,我的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.
       }
    }
}

1 个答案:

答案 0 :(得分:2)

Explicit Dependencies Principle之后,您可以确保将所有必要的依赖项注入到哪里。

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(...);

//...

如果使用Pure 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(...);

//...