Component: NServiceBus
NuGet Package NServiceBus (7-pre)
This page targets a pre-release version and is subject to change prior to the final release.

At its core NServiceBus is a library, as such it can be hosted in any .NET process.

There are several approaches to hosting.


"Self-hosting" is a general term used to refer to when the application code takes full control over all facets of hosting NServiceBus. This includes the following actions:

Override the default critical error callback when self-hosting NServiceBus. By default NServiceBus will stop the endpoint instance without exiting the process. Refer to the Critical Errors article for more information.


When self-hosting, the user is responsible for creating and starting the endpoint instance

var endpointConfiguration = new EndpointConfiguration("EndpointName");
// Apply configuration
var startableEndpoint = await Endpoint.Create(endpointConfiguration)
var endpointInstance = await startableEndpoint.Start()

// Shortcut
var endpointInstance2 = await Endpoint.Start(endpointConfiguration)

The user is also responsible for properly shutting down the endpoint when it is no longer needed (usually when the application terminates).

await endpointInstance.Stop().ConfigureAwait(false);
The endpoint instance is not disposable due to the asynchronous nature of the pipeline. Call Stop in an async manner (see example above).

Windows Service Hosting

A Windows Service is the most common way NServiceBus is hosted.


Send-only hosting

A "Send-only endpoint" is used when the only purpose is sending messages and no message processing is required in that endpoint. Common use cases include websites, console application and windows application. This is the code for starting an endpoint in send only mode.

var endpointConfiguration = new EndpointConfiguration("EndpointName");
var endpointInstance = await Endpoint.Start(endpointConfiguration)

The only configuration when running in this mode is the destination when Sending a message.

Web Hosting

NServiceBus can be hosted in any web technology that support .NET. See Web Application Hosting.

Service Fabric Hosting

Service Fabric can be used to host NServiceBus endpoints in several ways. See Service Fabric Hosting.


"Multi-hosting" refers to hosting multiple NServiceBus endpoints in a single .NET process.

It is safe for multiple endpoints can share the same AppDomain or, alternatively use a multiple AppDomains approach.


Accessing the bus

Most usages of the bus will occur where the NServiceBus APIs are used. For example Handlers and Sagas. However there are other scenarios that may require an alternative approach where the user needs to directly access the bus from outside of the framework.

Using dependency injection

NServiceBus supports dependency injection. At startup, the instance of a bus session will be injected into the configured dependency injection and can be access via that instance.


In Versions 6 and above, IEndpointInstance/IMessageSession (the equivalent of IBus in earlier versions) is no longer automatically injected via dependency injection. In order to send messages explicitly create a bus context. Here's a sample code showing how to automate this task using Autofac.
var containerBuilder = new ContainerBuilder();
var endpointConfiguration = new EndpointConfiguration("EndpointName");
var endpointInstance = await Endpoint.Start(endpointConfiguration)
containerBuilder.Register(_ => endpointInstance).InstancePerDependency();

Static variable

For many scenarios dependency injection is not required. In these cases a simple public static variable on the startup class will suffice. This variable can then be access globally in the application. For example:

  • In windows service or console the variable would be placed on the Program.cs
  • In a Website the variable would be placed on the Global.cs.

Alternatively the static variable could be placed on a (more appropriately named) helper class.

public static class EndpointInstance
    public static IEndpointInstance Endpoint { get; private set; }
    public static void SetInstance(IEndpointInstance endpoint)
        if (Endpoint != null)
            throw new Exception("Endpoint already set.");
        Endpoint = endpoint;

"Custom Host" Solutions

A "Custom Host" refers to a process or library that wraps the NServiceBus library to take partial control of configuration, startup and shutdown. This Host then exposes extension points for common activities and uses conventions and/or sensible defaults for many other configuration options.

NServiceBus Host

The NServiceBus Host takes a more opinionated approach to hosting. It allows the execution as both a windows service and a console application (for development). It also adds the concepts of Profiles and Custom installation.


Hosting in Azure

There are a variety of ways to host in Azure. Depending on the requirements self-hosting may be an option or, alternatively, a custom Azure host may be required. See Hosting in Azure Cloud Services for more information.


Startup diagnostics

To make troubleshooting easier, diagnostic information is collected during endpoint startup and written to a .diagnostics sub-folder in the host output directory.

By default, the output directory is called AppDomain.CurrentDomain.BaseDirectory, except for WebApps where App_Data is used instead.

To change the output path use:


At every endpoint startup the current diagnostics will be written to {endpointName}-configuration.txt. If possible attach this file(s) to support requests.

The structure and format of the data produced should not be considered stable or parsable. Nodes may be added, removed or moved in minor and patch versions.

Example content

Example partial content of the startup diagnostics (Formatted for readability).

  "AssemblyScanning": {
    "Assemblies": [
      "NServiceBus.Core, Version=, Culture=neutral, PublicKeyToken=9fc386479f8a226c"
    "ErrorsThrownDuringScanning": false,
    "SkippedFiles": []
  "Transport": {
    "Type": "NServiceBus.LearningTransport",
    "Version": "7.0.0"
  "Recoverability": {
    "ImmediateRetries": 5,
    "DelayedRetries": 3,
    "DelayedRetriesTimeIncrease": "0:00:10",
    "ErrorQueue": "error",
    "UnrecoverableExceptions": [

Writing to other targets

To take full control of how diagnostics are written use:

    diagnostics =>
        //custom logic to write data
        return Task.CompletedTask;

Adding startup diagnostics sections

To extend the startup diagnostics with custom sections use:

    sectionName: "MySection",
    section: new
        SomeSetting = "some data",
        SomeOtherSetting = 10

Settings can be accessed from a feature or via the endpoint configuration.

ILMerging NServiceBus assemblies

Since NServiceBus makes assumptions on aspects like assembly names, ILMerging any of the NServiceBus* assemblies is not supported.

Related Articles

Last modified