Autofac Dependency Injection Usage

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

Configuring to use Autofac

var busConfiguration = new BusConfiguration();
busConfiguration.EndpointName("Samples.Autofac");

var builder = new ContainerBuilder();
builder.RegisterInstance(new MyService());

builder
    .Register(x => Bus.Create(busConfiguration).Start())
    .SingleInstance();

using (var container = builder.Build())
{
    busConfiguration.UseContainer<AutofacBuilder>(
        customizations: customizations =>
        {
            // Child container needed as otherwise creation will hang
            var childContainer = container.BeginLifetimeScope();
            customizations.ExistingLifetimeScope(childContainer);
        });

Injecting the dependency in the handler

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

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

    public void Handle(MyMessage message)
    {
        myService.WriteHello();
    }
}

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