Autofac Dependency Injection Usage

Component: Autofac Dependency Injection
NuGet Package NServiceBus.Autofac (6.x)
Target NServiceBus Version: 6.x

Configuring an endpoint to use Autofac

var endpointConfiguration = new EndpointConfiguration("Samples.Autofac");

var builder = new ContainerBuilder();

IEndpointInstance endpoint = null;
builder.Register(x => endpoint)

builder.RegisterInstance(new MyService());

var container = builder.Build();

    customizations: customizations =>

Assign the local variable endpoint as shown below

endpoint = await Endpoint.Start(endpointConfiguration)

Injecting the dependency in the handler

public class MyHandler :
    MyService myService;

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

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

Related Articles

  • Autofac
    Details on how to Configure NServiceBus to use Autofac for dependency injection. Includes usage examples as well as lifecycle mappings.
  • Dependency Injection
    NServiceBus automatically registers components, handlers, and sagas.

Last modified