Getting Started
Architecture
NServiceBus
Transports
Persistence
ServiceInsight
ServicePulse
ServiceControl
Monitoring
Samples

Autofac Dependency Injection Usage

Target Version: NServiceBus 7.x
Standard support for version 7.x of NServiceBus has expired. For more information see our Support Policy.

Configuring an endpoint to use Autofac

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

endpointConfiguration.UseContainer(new AutofacServiceProviderFactory(containerBuilder =>
{
    containerBuilder.RegisterInstance(new MyService());
}));

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.
  • Dependency Injection
    NServiceBus automatically registers components, handlers, and sagas.