Endpoints multi hosting

Component: NServiceBus | Nuget: NServiceBus (Version: 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:

Edit
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 an Inversion of Control container is utilized to register all its components as well as user-implemented handlers, sagas and components; the container is automatically configured at start up scanning all the assemblies found in the directory where the program is executed from, in order to enforce that each bus instance registers only its own components it is important to specify an assembly scan policy using one of the supported approaches:

Edit
var endpointConfiguration = new EndpointConfiguration("Samples.MultiHosting.Instance1");
// Exclude Instance2.dll and, by inference, include all other assemblies
var assemblyScanner = endpointConfiguration.AssemblyScanner();
assemblyScanner.ExcludeAssemblies("Instance2");
endpointConfiguration.UseSerialization<JsonSerializer>();
endpointConfiguration.EnableInstallers();
endpointConfiguration.UsePersistence<InMemoryPersistence>();
endpointConfiguration.SendFailedMessagesTo("error");

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