Startup and Shutdown Sequence

Component: NServiceBus | Nuget: NServiceBus (Version: 5.x)

Code walk-through

Illustrates the order of startup shutdown operations including all extension points that plug into that process. So all interfaces that extend the startup and shutdown are included in an ExtensionPoints directory.

Logger

At each step in the process a line is written to both the console and a text file via a logger.

Edit
static class Logger
{
    static ILog log = LogManager.GetLogger(typeof(Logger));
    public static string OutputFilePath = Path.GetFullPath(@"..\..\..\StartupShutdownSequence.txt");
    static object locker = new object();

    static Logger()
    {
        AppDomain.CurrentDomain.ProcessExit += Exit;
        File.Delete(OutputFilePath);
        File.AppendAllText(OutputFilePath, "startcode");
        File.AppendAllText(OutputFilePath, " StartupShutdownSequence\r\n");
    }

    static void Exit(object sender, EventArgs e)
    {
        File.AppendAllText(OutputFilePath, "endcode");
    }

    public static void WriteLine(string message)
    {
        message = $"Thread:{Thread.CurrentThread.ManagedThreadId} {message}\r\n";
        log.Info(message);
        lock (locker)
        {
            File.AppendAllText(OutputFilePath, message);
        }
    }

}

Console Program

The main of the console Program configures and starts the bus while logging all these actions.

Edit
Logger.WriteLine("Starting configuration");
var busConfiguration = new BusConfiguration();
busConfiguration.EndpointName("Samples.StartupShutdown");
busConfiguration.EnableInstallers();
busConfiguration.EnableFeature<MyFeature>();
busConfiguration.UsePersistence<InMemoryPersistence>();

Logger.WriteLine("Calling Bus.Create");
using (var bus = Bus.Create(busConfiguration))
{
    Logger.WriteLine("Calling IStartableBus.Create");
    bus.Start();

    // simulate some activity
    Thread.Sleep(500);

    Logger.WriteLine("Bus is processing messages");
    Logger.WriteLine("Calling IStartableBus.Dispose");
}
Logger.WriteLine("Finished");

The resulting order

In some versions of NServiceBus certain extension points are executed on separate threads.
Edit
Thread:1 Starting configuration
Thread:1 Calling Bus.Create
Thread:1 Inside INeedInitialization.Customize
Thread:1 Inside IWantToRunBeforeConfigurationIsFinalized.Run
Thread:1 Inside Feature.Setup
Thread:1 Inside IWantToRunWhenConfigurationIsComplete.Run
Thread:1 Inside INeedToInstallSomething.Install
Thread:1 Inside IWantQueueCreated
Thread:1 Calling IStartableBus.Create
Thread:13 Inside IWantToRunWhenBusStartsAndStops.Start
Thread:5 Inside FeatureStartupTask.OnStart
Thread:1 Bus is processing messages
Thread:1 Calling IStartableBus.Dispose
Thread:5 Inside IWantToRunWhenBusStartsAndStops.Stop
Thread:1 Finished

Related Articles

  • Installers
    Installers ensure endpoint specific artifacts are installed and configured during endpoint startup.

Last modified