Search code examples
nservicebusnservicebus5

How to access NServiceBus dependency injection container?


I'm using NServiceBus 5's default dependency injection features. I want to register a singleton that depends on IBus in the endpoint config.

Ex:

configuration.RegisterComponents(r =>
{
  r.RegisterSingleton(new MyDependency(resolveIBus()));
  ...
}

How can I resolve the instance of IBus in the above pseduo code using NServiceBus's out-of-the-box dependency injection?


Solution

  • The correct syntax would be:

    configuration.RegisterComponents(r =>
    {
      r.ConfigureComponent<MyDependency>(DependencyLifecycle.SingleInstance);
      ...
    }
    

    The dependency mechanism will investigate the constructor(s) of the MyDependency type and chooses the simplest one it can completely resolve. So, you'll need to create your MyDependency type like this:

    public class MyDependency
    {
      public MyDependency(IBus bus)
      {
      }
    }
    

    More information in the NServiceBus Documentation

    If you only know what type of service you need at runtime, you can use the IServiceProvider service like this:

    public class MyDependency
    { 
      public MyDependency(IServiceProvider serviceProvider)
      { 
        ...
        var myService = (IMyService)serviceProvider.GetService(typeof(IMyService));
        ...
      }
    }