NServiceBus: specifying message order

拈花ヽ惹草 提交于 2019-12-01 07:33:06
Udi Dahan

As described in the NServiceBus FAQ on the documentation page:

http://docs.particular.net/nservicebus/handlers/handler-ordering

How do I specify the order in which handlers are invoked?

If you're writing your own host:

NServiceBus.Configure.With()
 ...
 .UnicastBus()
      .LoadMessageHandlers(First<H1>.Then<H2>().AndThen<H3>().AndThen<H4>() //etc)
 ...

If you're using the generic host

public class EndpointConfig : IConfigureThisEndpoint, ISpecifyMessageHandlerOrdering
{
     public void SpecifyOrder(Order order)
     {
          order.Specify(First<H1>.Then<H2>().AndThen<H3>().AndThen<H4>() //etc);
     }
}

If you only want to specify a single handler (with your own host)

NServiceBus.Configure.With()
     ...
     .UnicastBus()
          .LoadMessageHandlers<FIRST<YourHandler>>()
     ...

If you only want to specify a single handler (with the generic host)

public class EndpointConfig : IConfigureThisEndpoint, ISpecifyMessageHandlerOrdering
{
     public void SpecifyOrder(Order order)
     {
          order.Specify<FIRST<YourHandler>>();
     }
}

Another possibility would be to implement a base message handler class that would conditionally skip the handling based on your authentication check.

public abstract class MessageHandlerBase<T> : IMessageHandler<T> where T : IMessage
{
    public abstract void HandleMessage(T message);

    public void Handle(T message)
    {

        if (CredentialsValid(message))
            this.HandleMessage(message);

    }
}

Have you considered a message module for this purpose?

public interface IMessageModule
{
    // Methods
    void HandleBeginMessage();
    void HandleEndMessage();
    void HandleError();
}

Implementing this interface gives you a point to have code called before and after every message. If you inject an IBus, you can access the current message context, and from there inspect headers and use that to authenticate your messages.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!