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).

To use the host just create a new C# class library and reference the NServiceBus.Host NuGet package. The package also creates an example endpoint configuration and sets the NServiceBus.Host.exe as the startup project for the endpoint.

Configuring the endpoint

The NServiceBus.Host.exe scans the runtime directory for assemblies containing a class that implements the IConfigureThisEndpoint interface. This class will contain the configuration for this endpoint. Read more on how NServiceBus does assembly scanning.

To avoid the scanning process, configure the type of the endpoint configuration by adding the following to the NServiceBus.Host.exe.config file. The below example show the exact syntax:

7-pre NServiceBus.Host
<configuration>
  <appSettings>
    <add key="EndpointConfigurationType"
         value="YourNamespace.YourTypeName, YourAssembly"/>
  </appSettings>
</configuration>
4.x - 6.x NServiceBus.Host
<configuration>
  <appSettings>
    <add key="EndpointConfigurationType"
         value="YourNamespace.YourTypeName, YourAssembly"/>
  </appSettings>
</configuration>

Controlling assembly scanning using code

7-pre NServiceBus.Host
public class EndpointConfig :
    IConfigureThisEndpoint
{
    public void Customize(EndpointConfiguration endpointConfiguration)
    {
        // use 'busConfiguration' object to configure scanning
    }
}
5.x - 6.x NServiceBus.Host
public class EndpointConfig :
    IConfigureThisEndpoint
{
    public void Customize(BusConfiguration busConfiguration)
    {
        // use 'busConfiguration' object to configure scanning
    }
}
4.x NServiceBus.Host
public class EndpointConfig :
    IConfigureThisEndpoint,
    IWantCustomInitialization
{
    public void Init()
    {
        // use 'Configure' to configure scanning
    }
}

Controlling assembly scanning using the command line

A list of assemblies to scan can also be controlled using the /scannedAssemblies switch. If this option is used, the NServiceBus.Host.exe loads only assemblies that have been explicitly listed on the command line. Each assembly must be added using a separate switch:

NServiceBus.Host.exe /scannedAssemblies:"NServiceBus.Host" /scannedAssemblies:"MyMessages" /scannedAssemblies:"MyEndpoint"

The host loads the assemblies by invoking Assembly.Load method. This approach ensures that the specified assembly and all its dependent assemblies will also be loaded.

It is mandatory to include NServiceBus.Host in the /scannedAssemblies list as shown in the example above. As NServiceBus.Host references NServiceBus.Core, the latter can be safely omitted from the list.

Application Domains

The NServiceBus.Host.exe creates a separate service Application Domain to run NServiceBus and the user code. The new domain is assigned a configuration file named after the dll that contains the class implementing IConfigureThisEndpoint. All the configuration should be done in that file (as opposed to NServiceBus.Host.exe.config). In most cases that means just adding the app.config file to the project and letting MSBuild take care of renaming it while moving to the bin directory.

When the endpoint configuration is not specified explicitly, the host scans all the assemblies to find it and it does so in the context of the host application domain, not the new service domain. Because of that, when redirecting assembly versions, the assemblyBinding element needs to be present in both NServiceBus.Host.exe.config and app.config.

Custom initialization

For Versions 5 and above, customize the endpoint behavior using the IConfigureThisEndpoint.Customize method on the endpoint configuration class. Call the appropriate methods on the parameter passed to the method.

7-pre NServiceBus.Host
class CustomizingHost :
    IConfigureThisEndpoint
{
    public void Customize(EndpointConfiguration endpointConfiguration)
    {
        // To customize, use the configuration parameter.
        endpointConfiguration.UseSerialization<JsonSerializer>();
        endpointConfiguration.UsePersistence<InMemoryPersistence>();
    }
}
5.x - 6.x NServiceBus.Host
class CustomizingHost :
    IConfigureThisEndpoint
{
    public void Customize(BusConfiguration busConfiguration)
    {
        // To customize, use the configuration parameter.
        busConfiguration.UseSerialization<JsonSerializer>();
        busConfiguration.UsePersistence<InMemoryPersistence>();
    }
}

NServiceBus Version 4 and Version 3

To change core settings such as assembly scanning, container, and serialization format, implement IWantCustomInitialization on the endpoint configuration class (the same class that implements IConfigureThisEndpoint). Start the configuration expression with

Configure.With()
Do not perform any startup behaviors in the Init method.

After the custom initialization is done the regular core INeedInitalization implementations found will be called in the same way as when self hosting.

Startup Behavior

For Versions 7 and above, a new interface called IWantToRunWhenEndpointStartsAndStops has been added. This interface allows code to be executed at startup and shutdown of the Host. For Versions 6 and below, use the Endpoint Instance Start and Stop functionality`.

At startup, the Host invokes all the classes that implement the IWantToRunWhenEndpointStartsAndStopsinterface.

Implementations of IWantToRunWhenEndpointStartsAndStops are not started and stopped on a dedicated thread. They are executed on the thread starting and disposing the endpoint. It is the responsibility of the implementing class to execute its operations in parallel if needed (i.e. for CPU bound work). Failure to do so will prevent the endpoint from being started and/or disposed.
  • Instances of IWantToRunWhenEndpointStartsAndStops are located by assembly scanning and automatically registered into the configured container during endpoint creation. These are registered as Instance Per Call.
  • They are started before the transport and any satellites have started. Therefore the endpoint will not receive any messages until this process has completed.
  • These instances are created by the Container which means they:
    • Will have dependencies injected.
    • Do not require a default constructor.
  • These instances will be started asynchronously in the same method which started the bus.
  • Once created Start is called on each instance asynchronously without awaiting its completion.
  • Instances of IWantToRunWhenEndpointStartsAndStops which successfully start are kept internally to be stopped when the endpoint is stopped.
  • When the endpoint is shut down, the Stop method for each instance of IWantToRunWhenEndpointStartsAndStops is called asynchronously.
  • The instances will be stopped only after the transport and any satellites have stopped. While all instances of IWantToRunWhenEndpointStartsAndStops are being stopped, the endpoint will not handle any messages received.
  • The instances will be stopped asynchronously within the same method which disposed the endpoint.
The endpoint will not start processing messages until all instances of IWantToRunWhenEndpointStartsAndStops.Start are completed.
The Start and Stop methods will block start up and shut down of the endpoint. For any long running methods, use Task.Run so as not to block execution.
In NServiceBus Versions 6 and above, and all integrations that target those versions, all extension points that return Task cannot return a null Task. These APIs must return an instance of a Task. For example either a pending Task, a CompletedTask, or be marked async. For extension points that return a Task<T> return the value directly (for async methods) or wrap the value in a Task.FromResult(value).

Exceptions

Exceptions thrown in the constructors of instances of IWantToRunWhenEndpointStartsAndStops are unhandled by NServiceBus. These will prevent the endpoint from starting up.

Exceptions raised from the Start method will prevent the endpoint from starting. As they are called asynchronously and awaited with Task.WhenAll, an exception may prevent other Start methods from being called.

Exceptions raised from the Stop method will not prevent the endpoint from shutting down. The exceptions will be logged at the Fatal level.

Roles - Built-in configurations

As of Version 5 roles are obsoleted and should not be used. The functionality of AsA_Server, and AsA_Publisher has been made defaults in the core and can be safely removed. If the AsA_Client functionality is still required add the following configuration.

6.x NServiceBus.Host
var busConfiguration = new BusConfiguration();

busConfiguration.PurgeOnStartup(true);
busConfiguration.Transactions().Disable();
busConfiguration.DisableFeature<SecondLevelRetries>();
busConfiguration.DisableFeature<StorageDrivenPublishing>();
busConfiguration.DisableFeature<TimeoutManager>();

NServiceBus Version 4 and Version 3

The rest of the code specifying transport, subscription storage, and other technologies isn't here, because of the AsA_Server built-in configuration described next.

While NServiceBus allows picking and choosing which technologies to use and how to configure each of them, the host packages these choices into three built-in options: AsA_Client, AsA_Server, and AsA_Publisher. All these options make use of XmlSerializer, MsmqTransport, and UnicastBus. The difference is in the configuration:

  • AsA_Client sets MsmqTransport as non-transactional and purges its queue of messages on startup. This means that it starts afresh every time, not remembering anything before a crash. Also, it processes messages using its own permissions, not those of the message sender.
  • AsA_Server sets MsmqTransport as transactional and does not purge messages from its queue on startup. This makes it fault-tolerant.
  • AsA_Publisher extends AsA_Server and indicates to the infrastructure to set up storage for subscription requests, described in the profiles page.

Specify Endpoint Name

Namespace convention

When using NServiceBus.Host, the namespace of the class implementing IConfigureThisEndpoint will be used as the endpoint name as the default convention. In the following example the endpoint name when running NServiceBus host becomes MyServer. This is the recommended way to name a endpoint. Also this emphasizes convention over configuration approach.

7-pre NServiceBus.Host
namespace MyServer
{
    using NServiceBus;

    public class EndpointConfigByNamespace :
        IConfigureThisEndpoint,
        AsA_Server
    {
        // ... custom config
4.x - 6.x NServiceBus.Host
namespace MyServer
{
    using NServiceBus;

    public class EndpointConfigByNamespace :
        IConfigureThisEndpoint,
        AsA_Server
    {
        // ... custom config

Defined in code

Set the endpoint name using the DefineEndpointName(name) extension method on the endpoint configuration.

7-pre NServiceBus.Host
public void Customize(EndpointConfiguration configuration)
{
    configuration.DefineEndpointName("CustomEndpointName");
}

EndpointName attribute

Set the endpoint name using the [EndpointName] attribute on the endpoint configuration.

This will only work when using NServiceBus host.
7-pre NServiceBus.Host
[EndpointName("MyEndpointName")]
public class EndpointConfigWithAttribute :
    IConfigureThisEndpoint, AsA_Server
{
    // ... custom config
5.x - 6.x NServiceBus.Host
[EndpointName("MyEndpointName")]
public class EndpointConfigWithAttribute :
    IConfigureThisEndpoint,
    AsA_Server
{
    // ... the config
4.x NServiceBus.Host
[EndpointName("MyEndpointName")]
public class EndpointConfigWithAttribute :
    IConfigureThisEndpoint,
    AsA_Server
{
    // ... custom config

Default Critical error action handling

The default Critical Error Action for the Host is:

7-pre NServiceBus.Host
if (Environment.UserInteractive)
{
    // so that user can see on their screen the problem
    Thread.Sleep(10000);
}

string fatalMessage = $"NServiceBus critical error:\n{errorMessage}\nShutting down.";
Environment.FailFast(fatalMessage, exception);
4.x - 6.x NServiceBus.Host
if (Environment.UserInteractive)
{
    // so that user can see on their screen the problem
    Thread.Sleep(10000);
}

var fatalMessage = $"NServiceBus critical error:\n{errorMessage}\nShutting down.";
Environment.FailFast(fatalMessage, exception);
It is important to consider the effect these defaults will have on other things hosted in the same process. For example if co-hosting NServiceBus with a web-service or website.

Samples

Related Articles


Last modified