In a hosted endpoint, we don't have to do anything to start the bus; that is handled for us. We only set options on the BusConfiguration
object. When self-hosting, however, we have to explicitly start the bus ourselves. Back in our example code, we had this line:
IBus Bus = NServiceBus.Bus.Create(cfg).Start();
It really can't get any simpler than that. The Create()
method returns an IStartableBus
instance, which we can then start to return the IBus
instance to share it with the rest of our application.
The IStartableBus
interface implements IDisposable
, which means we can use it in a using
block if we only need the bus for a short time for some reason. For most applications, however, the bus's lifetime will mirror that of the host app. The IBus
instance is fairly expensive to create (as the length of this chapter can attest), so you won't want to create a new instance every time some action occurs. Instead, create it when the application starts up and dispose it when the application...