Ninject

Project Hosting | Nuget: NServiceBus.Ninject (Version: 6.x)
Target NServiceBus Version: 6.x

NServiceBus can be configured to use Ninject as a dependency injection container.

Default Usage

Edit
endpointConfiguration.UseContainer<NinjectBuilder>();

Existing Container Instance

Edit
var kernel = new StandardKernel();
kernel.Bind<MyService>()
    .ToConstant(new MyService());
endpointConfiguration.UseContainer<NinjectBuilder>(
    customizations: customizations =>
    {
        customizations.ExistingKernel(kernel);
    });

Unit of work

Its is possible to bind to use an Unit of Work scope, which corresponds to the DependencyLifecycle.InstancePerUnitOfWork lifecycle, when registering components with configuration.RegisterComponents(...).

In essence, bindings using Unit of Work scope

  • will be instantiated only once per transport Message
  • will be disposed when message processing finishes

Bind the services in Unit of Work scope using:

Edit
var kernel = new StandardKernel();

kernel.Bind<MyService>()
    .ToSelf()
    .InUnitOfWorkScope();

Services using InUnitOfWorkScope() can only be injected into code which is processing messages. To inject the service somewhere else (e.g. because of an user interaction) define conditional bindings:

Edit
var kernel = new StandardKernel();

// always create a new instance when not processing a message
kernel.Bind<MyService>().ToSelf()
    .WhenNotInUnitOfWork()
    .InTransientScope();

// always use the same instance when processing messages
kernel.Bind<MyService>().ToSelf()
    .WhenInUnitOfWork()
    .InSingletonScope();

DependencyLifecycle Mapping

The DependencyLifecycle maps to Ninject in the following way.

DependencyLifecycleNinject Equivalent
InstancePerCallTransient
InstancePerUnitOfWorkSingleton within a Named Scope per Unit of Work
SingleInstanceSingleton

Related Articles

  • Child Containers
    Child containers are a snapshot of the main container; transient instances are treated as as singletons in the child container.

Last modified