Endpoints multi hosting

Component: NServiceBus
NuGet Package NServiceBus (6.x)

Code walk-through

This sample shows how to host multiple endpoints in one process. At start up the application creates two endpoint instances, connected to different queues using different configurations:

IEndpointInstance endpoint1 = null;
IEndpointInstance endpoint2 = null;
try
{
    endpoint1 = await StartInstance1()
        .ConfigureAwait(false);
    endpoint2 = await StartInstance2()
        .ConfigureAwait(false);

    Console.WriteLine("Press '1' to send a message from Instance1 to Instance2");
    Console.WriteLine("Press '2' to send a message from Instance2 to Instance1");
    Console.WriteLine("Press any key to exit");

    while (true)
    {
        var key = Console.ReadKey();
        Console.WriteLine();
        var message = new MyMessage();
        if (key.Key == ConsoleKey.D1)
        {
            await endpoint1.Send("Samples.MultiHosting.Instance2", message)
                .ConfigureAwait(false);
            continue;
        }
        if (key.Key == ConsoleKey.D2)
        {
            await endpoint2.Send("Samples.MultiHosting.Instance1", message)
                .ConfigureAwait(false);
            continue;
        }
        return;
    }
}
finally
{
    if (endpoint1 != null)
    {
        await endpoint1.Stop()
            .ConfigureAwait(false);
    }
    if (endpoint2 != null)
    {
        await endpoint2.Stop()
            .ConfigureAwait(false);
    }
}

One important thing to keep in mind is that internally dependency injection is used to register components, handlers, and sagas; dependency injection is automatically configured at start up to scan all the assemblies found in the directory where the program is executed from. In order to ensure that each endpoint instance registers only its own components, it is important to specify an assembly scan policy using one of the supported approaches:

var endpointConfiguration = new EndpointConfiguration("Samples.MultiHosting.Instance1");
// Exclude Instance2.dll and, by inference, include all other assemblies
var scanner = endpointConfiguration.AssemblyScanner();
scanner.ExcludeAssemblies("Instance2");
endpointConfiguration.UsePersistence<LearningPersistence>();
endpointConfiguration.UseTransport<LearningTransport>();

return Endpoint.Start(endpointConfiguration);
This is possible only when self-hosting and not using NServiceBus.Host

Related Articles

  • Assembly scanning
    To enable automatic detection of various features NServiceBus scans assemblies for well known types.
  • Hosting
    Outlines the various approaches to endpoint hosting.

Last modified