Autofac Container Usage

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

Configuring NServiceBus to use the container

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 as a container. Includes usage examples as well as lifecycle mappings.
  • Containers
    NServiceBus automatically registers components, handlers, and sagas.

Last modified