Endpoints multi hosting

Component: NServiceBus | Nuget: NServiceBus (Version: 5.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
using (var bus1 = StartInstance1())
using (var bus2 = StartInstance2())
{
    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();
        if (key.Key == ConsoleKey.D1)
        {
            bus1.Send("Samples.MultiHosting.Instance2", new MyMessage());
            continue;
        }
        if (key.Key == ConsoleKey.D2)
        {
            bus2.Send("Samples.MultiHosting.Instance1", new MyMessage());
            continue;
        }
        return;
    }
}

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 busConfiguration = new BusConfiguration();

busConfiguration.EndpointName("Samples.MultiHosting.Instance1");
// only include Instance1.dll and dependent assemblies
busConfiguration.AssembliesToScan(AllAssemblies.Matching("Instance1.").And("Shared"));
busConfiguration.UseSerialization<JsonSerializer>();
busConfiguration.EnableInstallers();
busConfiguration.UsePersistence<InMemoryPersistence>();

return Bus.Create(busConfiguration).Start();
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