NServiceBus.Extensions.DependencyInjection Usage

Configuring an endpoint to use ServiceProvider

The following code configures an endpoint using Microsoft's built-in dependency injection container:

var endpointConfiguration = new EndpointConfiguration("Samples.NServiceBus.Extensions.DependencyInjection");

// Use the default ServiceProvider factory, using Microsoft's built-in DI container:
var containerSettings = endpointConfiguration.UseContainer(new DefaultServiceProviderFactory());
containerSettings.ServiceCollection.AddSingleton(new MyService());

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


Last modified