Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

Spring Dependency Injection Usage

NuGet Package: NServiceBus.Spring (8.x)
Target Version: NServiceBus 7.x

Configuring an endpoint to use Spring

var endpointConfiguration = new EndpointConfiguration("Samples.Spring");
var applicationContext = new GenericApplicationContext();
applicationContext.ObjectFactory
    .RegisterSingleton("MyService", new MyService());
endpointConfiguration.UseContainer<SpringBuilder>(
    customizations: customizations =>
    {
        customizations.ExistingApplicationContext(applicationContext);
    });

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

  • Dependency Injection
    NServiceBus automatically registers components, handlers, and sagas.
  • Spring
    Details on how to Configure NServiceBus to use Spring for dependency injection.