At one of my clients, I recently demonstrated how to use Topshelf to create Windows Services and how to deploy the Windows Service using TeamCity and Octopus Deploy. In this blog, I wanted to demonstrate how to use Topshelf to create a Window Service and how to deploy the Windows Service using TeamCity and Octopus Deploy.
Assumptions!
- You are already familiar with TeamCity
- You are already have a Octopus Deploy Server up and running
- You already have a TeamCity Server version 2017.1+ up and running
- You are already familiar with Windows Services
- You are already familiar with Topshelf
Project Structure!
I created a simple Windows Service using Topshelf that runs every 10 seconds and writes a list of movies to json files. The code can be found on GitHub here. I started by creating a new Console Application and then installing the Topshelf NuGet Package.
Here is my project structure:
Here is my code to configure Topshelf in Program.cs:
namespace TopShelfWindowsService
{
class Program
{
static void Main(string[] args)
{
var rc = HostFactory.Run(x =>
{
x.Service(s =>
{
s.ConstructUsing(name => new MyService());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();
x.StartAutomatically();
x.SetDescription("Sample Topshelf Host");
x.SetDisplayName("TopshelfWindowsService");
x.SetServiceName("TopshelfWindowsService");
});
var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());
Environment.ExitCode = exitCode;
}
}
}
You will need to install the OctoPack NuGet Package in your Topshelf Console Application to be able to deploy the Windows Service using Octopus Deploy.
TeamCity!
In TeamCity, create a new Project and configure the VCS Root:
Next, create a new Build Configuration for the Project and create 4 Build Configuration Steps:
Build Configuration:
Build steps:
I also added the VCS Root that I created when I created the Project and I added a Trigger to kickoff the Build & Deploy whenever code is checked in to the GitHub repository.
Octopus Deploy!
In Octopus Deploy, add a new project, add a step and choose Deploy a Windows Service. Below is how I configured the Octopus Deploy Windows Service Template:
For the Windows Service: Executable Section, you will need to provide the path to the Windows Service exe and the servicename argument must be the same name you gave your service in the Topshelf Configuration, in my case it is TopShelfWindowsService.
Adding my variable I created to change the output directory of the json files.:
Result!
Now that I have my Windows Service created and TeamCity and Octopus Deploy setup, I am going to run the project in TeamCity and see if the Windows Service gets deployed and is running correctly.
TeamCity Build & Deploy is successful:
Octopus Deploy has completed successfully:
Checking Services under Administrative Tools, I can see that the Windows Service has been installed and is running:
Checking the output directoy, I can see that json files are being generated: