Dependency Injection

Services and state are managed by Dependency Injection (DI). NServiceBus automatically registers all its components as well as user-implemented handlers and sagas so that all instancing modes and wiring are done correctly by default and without errors. NServiceBus has a built-in DI, but it can be replaced by any other container.

SingleInstance

The same instance will be returned each time.

Represented by the enum value DependencyLifecycle.SingleInstance.

SingleInstance components that have dependencies that are scoped InstancePerCall or InstancePerUnitOfWork will still resolve. In effect these dependencies, while not scoped SingleInstance, will behave as if they are SingleInstance as the instances will exist inside the parent component.

Supported

Using an existing instance

The above pages all have examples of how to pass in an instance. This is useful to make use of the full features and share the behavior with NServiceBus.

Endpoint resolution

Note that all NServiceBus services will be injected into the passed in dependency injection instance. As such there is no need to register these instances at configuration time.

IEndpointInstance needs to be registered to be properly resolved.

Cleanup

In Version 6 IEndpointInstance is not IDisposable.

Plugging in

If a specific library is not already supported, then create a plugin using the IContainer abstraction. Once this is created and registered, NServiceBus will use the custom dependency injection to look up its own dependencies.