Unity Dependency Injection Usage

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

Configuring to use Unity

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

var container = new UnityContainer();
container.RegisterInstance(new MyService());
busConfiguration.UseContainer<UnityBuilder>(
    customizations: customizations =>
    {
        customizations.UseExistingContainer(container);
    });

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

  • Dependency Injection
    NServiceBus automatically registers components, handlers, and sagas.
  • Unity
    Details on how to Configure NServiceBus to use Unity for dependency injection. Includes usage examples as well as lifecycle mappings.

Last modified