Message lifetime scoped behaviors

Currently, NServiceBus has Behavior which uses singletons injections.

It would be incredibly helpful if there was a ScopedBehavior that works in the message lifetime-- or if not that, then, in Behavior, have a way to programmatically access the message lifetime scoped context to be able to register into it and inject from it.

Or, is there some other preferred way to do this? I thought about creating a CustomHandleMessages extending IHandleMessages. Then, I would have all my handlers extend CustomHandleMessages. CustomHandleMessages.Handle() would then be able to do some work on messages , then call then subclass’s handle logic, and then do some more wrap-up work.

Hi @mech

You are correct by mentioning the Behavior constructor injection uses singleton lifetime. This is a performance tradeoff to make sure behavior do not get created for every pipeline invocation. This saves a ton of unnecessary allocations in the majority of pipeline use cases.

It is possible though to get access to scoped dependencies in the incoming pipeline by using the service provider available on the context.

public class BehaviorUsingTheProvider :
    Behavior<IIncomingLogicalMessageContext>
{
    public override Task Invoke(IIncomingLogicalMessageContext context, Func<Task> next)
    {
        var yourService = context.Builder.GetRequiredService<YourService>();

        await next();
    }
}

Does that work for you? I’m currently checking whether we have a sample on our documentation page or not. If we don’t have one, I will also update our pipeline documentation to mention this for any other person asking a similar question. Stay tuned.

I thought about creating a CustomHandleMessages extending IHandleMessages. Then, I would have all my handlers extend CustomHandleMessages. CustomHandleMessages.Handle() would then be able to do some work on messages , then call then subclass’s handle logic, and then do some more wrap-up work.

Would you mind elaborating a bit more what you are trying to solve with this custom handler? We might be able to give you solutions that don’t require your own dedicated approach, depending on the use case.

Regards,
Daniel

I have created a pull request that documents how DI works with behaviors

Once the PR is merged, the changes will be visible on the pipeline documentation pages.

Daniel