Autofac Dependency Injection Usage

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

Configuring to use Autofac

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

var builder = new ContainerBuilder();

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

builder.RegisterInstance(new MyService());

var container = builder.Build();

endpointConfiguration.UseContainer<AutofacBuilder>(
    customizations: customizations =>
    {
        customizations.ExistingLifetimeScope(container);
    });

Assign the local variable endpoint as shown below

endpoint = await Endpoint.Start(endpointConfiguration)
    .ConfigureAwait(false);

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

  • 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