Starting with NServiceBus version 7, the dependency injection container adapter packages are no longer required. NServiceBus directly supports the Microsoft.
model and third party containers can be integrated using the NServiceBus.Extensions.DependencyInjection package or via the .NET Generic Host.
In NServiceBus version 8, NServiceBus will no longer provide adapters for external dependency injection containers.
Visit the dependency injection upgrade guide for further information.
NServiceBus can be configured to use Ninject for dependency injection.
Default usage
endpointConfiguration.UseContainer<NinjectBuilder>();
Using an existing kernel
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.
lifecycle, when registering components with configuration.
.
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:
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:
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();
Funcs can only be injected when using the ContextPreservation Ninject extension.
var kernel = new StandardKernel();
kernel.Bind<MyService>()
.ToMethod(ctx => ctx.ContextPreservingGet<MyService>())
.InUnitOfWorkScope();
Multi hosting
Multiple endpoints in a single process cannot share a single Ninject kernel. Each requires its own container instance or each requires its own child container. Ninject supports this with the Ninject.Extensions.ChildKernel extension. Execute new ChildKernel(parentKernel)
and pass this new kernel instance to NServiceBus.
DependencyLifecycle Mapping
DependencyLifecycle
maps to Ninject object scopes as follows:
DependencyLifecycle | Ninject object scope |
---|---|
InstancePerCall | Transient |
InstancePerUnitOfWork | Singleton within a Named Scope per Unit of Work |
SingleInstance | Singleton |
Property Injection
This dependency injection container adapter automatically enables property injection for known types. Use the Func
overload of .
to get full control over the injected properties if needed.