Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

NServiceBus.Extensions.DependencyInjection Usage

Configuring an endpoint to use ServiceProvider

The following code configures an endpoint with the externally managed mode using Microsoft's built-in dependency injection container:

var serviceCollection = new ServiceCollection();
serviceCollection.AddSingleton<MyService>();
serviceCollection.AddSingleton<MessageSenderService>();

var endpointWithExternallyManagedServiceProvider = EndpointWithExternallyManagedServiceProvider
    .Create(endpointConfiguration, serviceCollection);
// if needed register the session
serviceCollection.AddSingleton(p => endpointWithExternallyManagedServiceProvider.MessageSession.Value);

Injecting the message session into dependencies

public class MessageSenderService
{
    private readonly IMessageSession messageSession;

    public MessageSenderService(IMessageSession messageSession)
    {
        this.messageSession = messageSession;
    }

    public Task SendMessage()
    {
        var myMessage = new MyMessage();
        return messageSession.SendLocal(myMessage);
    }
}

Injecting the dependency in the handler

public class MyHandler :
    IHandleMessages<MyMessage>
{
    MyService myService;

    public MyHandler(MyService myService)
    {
        this.myService = myService;
    }

    public Task Handle(MyMessage message, IMessageHandlerContext context)
    {
        myService.WriteHello();
        return Task.CompletedTask;
    }
}

Related Articles