Hosting using the NServiceBus.Host

Component: NServiceBus Host
NuGet NServiceBus.Host (6.x)
Target NServiceBus Version: 5.x

Code walk-through

This sample shows how to host a NServiceBus endpoint using the NServiceBus.Host.

[EndpointName("Samples.NServiceBus.Host")]
public class EndpointConfig :
    IConfigureThisEndpoint
{
    public void Customize(BusConfiguration busConfiguration)
    {
        busConfiguration.UseSerialization<JsonSerializer>();
        busConfiguration.EnableInstallers();
        busConfiguration.UsePersistence<InMemoryPersistence>();
    }
}

Running code when at start and stop

Since the configuration is done via an implementation of IConfigureThisEndpoint and the host controls the startup process there is no regular way to run code at startup and stop of the endpoint. To enable this scenario there is an interface that is assembly scanned and executed at these times.

public class MessageSender :
    IWantToRunWhenBusStartsAndStops
{
    IBus bus;

    public MessageSender(IBus bus)
    {
        this.bus = bus;
    }

    public void Start()
    {
        var myMessage = new MyMessage();
        bus.SendLocal(myMessage);
    }

    public void Stop()
    {
    }
}

Related Articles

  • Interface life-cycles
    The life-cycles of the various NServiceBus configuration interfaces.
  • NServiceBus Host
    Avoid writing repeat configuration code, host the endpoints in a Windows Service, and change technologies without code.

Last modified