Alwyn
Alwyn

Reputation: 8337

AoP support in NServiceBus?

Ties back to my old question here:

But I really want to intercept messages AND have an instance of the handler and be able to influence the whether the message should go to the handler at all. Basically an "around advice".

Now the most traditional way of implementing something like this is via dynamic inheritance of the target object and overriding the virtual methods. The thing that I could not tell due to lack of documentation whether, NServiceBus creates or builds up its message handler instances. If it builds up, then it can't dynamically inherit, so most AoP framework is probably out of the question, otherwise most popular DI container should do the trick.

However testing with Saga handers it seems like NServiceBus builds up rather than creates new due to the requirement for a default constructor, which points to NServiceBus manually activating the class.

Yes I realize I can use good ole' OOP to solve the same problem, but I usually prefer AoP for better (less) coupling.


Upvotes: 1

Views: 296

Answers (2)

MeTitus
MeTitus

Reputation: 3428

Old post, but someone looking for a way to get AOP with NServiceBus, here's a different way of doing it:

https://github.com/MeTitus/NServiceBus/commit/278b6bf4e3daba2fbdfc5295b8718609946d653d

The other way is to user PostSharp.

Upvotes: 0

Chris Bednarski
Chris Bednarski

Reputation: 3424

If all you want to do is influence if a message should go to a handler or not, then NServiceBus provides a solution for that => DoNotContinueDispatchingCurrentMessageToHandlers()

You can create a generic handler and set it up to fire before any other handlers.

public class SomeHandler: IHandleMessages<object>, ISpecifyMessageHandlerOrdering
{
    public IBus Bus {get;set;}

    public void Handle(object message)
    {
        Bus.DoNotContinueDispatchingCurrentMessageToHandlers();
    }

    public void SpecifyOrder(Order order)
    {
        order.SpecifyFirst<SomeHandler>();
    }
}

For more details see this answer

Alternatively, this can be plugged in as a mutator

class StopThePipelineMutator: IMutateIncomingTransportMessages,INeedInitialization
{
    public IBus Bus { get; set; }

    public void MutateIncoming(TransportMessage transportMessage)
    {
        Bus.DoNotContinueDispatchingCurrentMessageToHandlers();    
    }

    public void Init()
    {
       Configure.Component<StopThePipelineMutator>(DependencyLifecycle.InstancePerCall);
    }
}

Upvotes: 6

Related Questions