Autofac Container Usage

Component: Autofac Container | Nuget: NServiceBus.Autofac (Version: 6.x)
Target NServiceBus Version: 6.x

Configuring NServiceBus to use the container

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

var builder = new ContainerBuilder();
builder.RegisterInstance(new MyService());
var container = builder.Build();
endpointConfiguration.UseContainer<AutofacBuilder>(
    customizations: customizations =>
    {
        customizations.ExistingLifetimeScope(container);
    });

Injecting the dependency in the handler

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

Last modified