Software Architect / Microsoft MVP (AI) and Technical Author

C#, General Development, Process Improvement, Prototyping, Tooling

How to simplify Windows Service development using Topshelf

Introduction

Sometimes you need to have a process that runs continually in the background on your server or infrastructure 24×7.  Windows Services can help you do this and are easy to build in .NET.  You write your custom code, implement the OnStart/OnStop events and setup your Timer to fire said custom code at specific intervals.

This is fine and works well.

The bit that I find to be a pain as I’m going through the development phase is the install / uninstall process as you build functionality.

It’s often done through the developer command prompt using the following syntax:

Install

InstallUtil.exe "c:\myservice.exe"

UnInstall

InstallUtil.exe /u "c:\myservice.exe"

It’s not a massive amount of effort but continually doing this as you develop/debug your Windows service it soon starts to frustrate.

frustratedDeveloper

Enter Topshelf

Topshelf is an open source Windows Service framework that saves the developer from having to go through the install/uninstall process repeatedly.  I’ve found Topshelf speeds up the development/debugging cycle as I’m not messing around with batch files or the command prompt just to test a few amendments to my Windows service.

Nor do I have to attach my Visual Studio debugger to a Windows Service process!

You can get Topshelf from the NuGet Gallery here.

How does it Work?

Topshelf is easy to use, it allows you  develop your Windows service as a Console Application.  The main steps are:

  1. Create a Console application and add the Topshelf NuGet package to it.
  2. Create a Class to Contain the Service logic class (this needs to implement OnStart and OnStop events).
  3. Setup Topshelf configuration.

How do I implement it?

You can find more detailed information to help you configure Topshelf on the project site but the following code snippets will give you the basics in terms of implementing it very quickly.

These code snippets show you the basic Topshelf Configuration within a Console Application that invokes a custom Service Class.  I used something similar to this when building/testing a Windows Service that would extract content periodically from social media channels.

 class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>                                 
            {
                x.Service(s =>                        
                {
                    s.ConstructUsing(name => new SampleService());     
                    s.WhenStarted(tc => tc.Start());              
                    s.WhenStopped(tc => tc.Stop());               
                });
                x.RunAsLocalSystem();                            

                x.SetDescription("My test service that runs using Topshelf");        
                x.SetDisplayName("MyService");                       
                x.SetServiceName("My service name");                       
            });

        }
    }
   public class SampleService
    {
        private System.Timers.Timer _timer;
        private int _requestCount = 0;
        private TimeSpan _counter = new TimeSpan();
     
        public SampleService()
        {
            double interval = 120000; // 2 mins
            _timer = new Timer(interval);
            _timer.Elapsed += new ElapsedEventHandler(OnTick);
        }

        public void Start()
        {
            _timer.AutoReset = true;
            _timer.Enabled = true;
            _timer.Start();
            OnTick(null, null);
        }

        public void Stop()
        {
            _timer.AutoReset = false;
            _timer.Enabled = false;
        }

        protected virtual void OnTick(object sender, ElapsedEventArgs e)
        {
			// your custom code here
        }
    }

In this code you can see I’ve setup the OnStart OnStop events as well as a Timer to execute my code every few minutes.  This is the service (your Windows service!) that will be started when the Topshelf configuration is loaded.

Testing your new service is simple now.  Simply place your breakpoints and hit F5 to run the Console Application and debug the code that forms your Windows Service.

No more command line/batch files or installers whilst you refine your Windows Service.

When you complete development of your Windows Service you can migrate this code into your Windows Service project.

Have you used Topshelf and found it useful?

JOIN MY EXCLUSIVE EMAIL LIST
Get the latest content and code from the blog posts!
I respect your privacy. No spam. Ever.

Leave a Reply