Externally Managed Mode

Component: NServiceBus
NuGet Package: NServiceBus (8-pre)
This page targets a pre-release version. Pre-releases are subject to change and samples are not guaranteed to be fully functional.

Configuring the endpoint

The sample configures an endpoint to use externally managed mode with Microsoft's dependency injection container and registers some dependencies.

// ServiceCollection is provided by Microsoft.Extensions.DependencyInjection
var serviceCollection = new ServiceCollection();

// most dependencies may now be registered

// EndpointWithExternallyManagedContainer.Create accepts an IServiceCollection,
// which is inherited by ServiceCollection
var endpointWithExternallyManagedContainer = EndpointWithExternallyManagedContainer
    .Create(endpointConfiguration, serviceCollection);

// if IMessageSession is required as dependency, it may now be registered
serviceCollection.AddSingleton(p => endpointWithExternallyManagedContainer.MessageSession.Value);

Injecting dependencies into handlers

Registered dependencies may be injected into message handlers using constructor injection:

public class MyHandler :
    private readonly Greeter greeter;

    public MyHandler(Greeter greeter) =>
        this.greeter = greeter;

    public Task Handle(MyMessage message, IMessageHandlerContext context)
        return Task.CompletedTask;

Injecting the message session into other types

When IMessageSession has been registered as shown above, it may be injected into other types using constructor injection:

public class MessageSender
    private readonly IMessageSession messageSession;

    public MessageSender(IMessageSession messageSession) =>
        this.messageSession = messageSession;

    public Task SendMessage()
        var myMessage = new MyMessage();
        return messageSession.SendLocal(myMessage);
An IMessageSession may only be injected by the container after the endpoint has been started.

Related Articles

Last modified