Endpoints multi hosting

Component: NServiceBus
NuGet Package NServiceBus (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:

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();
        if (key.Key == ConsoleKey.D1)
            bus1.Send("Samples.MultiHosting.Instance2", new MyMessage());
        if (key.Key == ConsoleKey.D2)
            bus2.Send("Samples.MultiHosting.Instance1", new MyMessage());

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

// only include Instance1.dll and dependent assemblies

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
    Describes the various approaches to endpoint hosting.

Last modified