Hosting in a Windows Service

Component: NServiceBus
NuGet Package NServiceBus (5.x)

Code walk-through

This sample shows how to host NServiceBus as a Windows Service in process with support for streamlined debugging experience from Visual Studio.

NServiceBus comes with a host exe that abstracts much of the hosting complexity. Its many features include installation, un-installation and configuring the windows service. It provides these features though a reasonable amount of custom code and the use of some powerful libraries like TopShelf. Since the NServiceBus Host is a general solution with dependencies there are some drawback associated with using it.

The sample is a console application whose Main entry point detects if the application is run in interactive mode or not; when run in interactive mode the service is manually created and invoked as any other C# class instance, otherwise the Run method is called to invoke the base ServiceBase class API.

static void Main()
{
    Console.Title = "Samples.WindowsServiceAndConsole";
    using (var service = new ProgramService())
    {
        if (Environment.UserInteractive)
        {
            service.OnStart(null);

            Console.WriteLine("Bus started. Press any key to exit");
            Console.ReadKey();

            service.OnStop();

            return;
        }
        Run(service);
    }
}

The OnStart method, manually called when running in interactive mode and automatically called by the Windows Service when running as service, configures the Endpoint Instance:

protected override void OnStart(string[] args)
{
    var busConfiguration = new BusConfiguration();

    busConfiguration.EndpointName("Samples.WindowsServiceAndConsole");
    busConfiguration.UsePersistence<InMemoryPersistence>();
    busConfiguration.EnableInstallers();
    bus = Bus.Create(busConfiguration).Start();

    // run any startup actions on the bus
    var myMessage = new MyMessage();
    bus.SendLocal(myMessage);
}

When the interactive application is shut down or the Windows Service is stopped the OnStop method is called perform the required clean up:

protected override void OnStop()
{
    bus?.Dispose();
}

Related Articles

  • Hosting
    Outlines the various approaches to endpoint hosting.

Last modified