Welcome

You have reached the blog of Keith Elder. Thank you for visiting! Feel free to click the twitter icon to the right and follow me on twitter.

How To Build Windows Services in .NET The Easy Way with Topshelf–Part 1

Posted by Keith Elder | Posted in .Net, Windows, Windows Service | Posted on 12-02-2011

8

Building a Windows Service is something most .NET developers will have to do at one point or another.  While not too terribly difficult to understand and build there is a little bit of a learning curve to build one.  That’s not the hard part though.  The hard part is debugging a Windows Service.  It can be very painful.  There is an easier way that I’ve recently discovered that more developers need to know is available.  I’m talking about Topshelf.

Topshelf is a cross-platform (Windows and Mono) open source project that allows developers to build Windows Services as Console applications (which are WAY easier to debug) and then run their program as a Console application or as a Windows Service.  As if that wasn’t enough Topshelf also allows one to xcopy deploy Windows Services.  I know, crazy huh! Here is a brief walkthrough on how it works.

Step 1

Download and unzip the Topshelf files.

The current version can be downloaded from the following location:

 http://github.com/downloads/Topshelf/Topshelf/Topshelf.v2.0.0.0.zip

or

NuGet can be used to install Topshelf if you have NuGet installed.

PM> Install-Package TopShelf

http://nuget.org/Packages/Packages/Details/TopShelf-2-1-0-85

For this walkthrough I’ll assume you don’t have NuGet installed.

Step 2

Create a Console Application in Visual Studio

Step 3

Right click in Visual Studio on “References” and “Add reference” to the Topshelf.dll you just unzipped.

Step 4

Now the fun part.  Add a class to your project.  In that class add two methods called Stop() and Start().  These methods will be called when your console application is started and stopped or when the Windows Service is started and stopped.

   1: public class WordsofWisdomService

   2: {

   3:     public void Start()

   4:     {

   5:         Console.WriteLine("Starting Words of Wisdom...");

   6:     }

   7:  

   8:     public void Stop()

   9:     {

  10:         Console.WriteLine("Shutting down Words of Wisdom...");

  11:     }

  12: }

To show the proof of concept all I’m doing is printing to the console when these methods are called.

Step 5

Open the Program.cs file in the project and in the main function copy paste the code below.  This will wire up the above class to Topshelf. 

This tells Topshelf all it needs to know about what will become our Windows Service including description, name and so on.  Here’s a sample, reading it should be pretty self-explanatory.

   1: static void Main(string[] args)

   2:         {

   3:             RunConfiguration cfg = RunnerConfigurator.New(x =>

   4:                 {

   5:                     x.ConfigureService<WordsofWisdomService>(s =>

   6:                         {

   7:                             s.Named("WordsOfWisdom");

   8:                             s.HowToBuildService(name => new WordsofWisdomService());

   9:                             s.WhenStarted(ls => ls.Start());

  10:                             s.WhenStopped(ls => ls.Stop());

  11:                         }

  12:                         );

  13:                     x.RunAsLocalSystem();

  14:                     x.SetDescription("This service returns words of wisdom when asked.");

  15:                     x.SetDisplayName("WordsOfWisdom");

  16:                     x.SetServiceName("WordsOfWisdom");

  17:                 });

  18:             Runner.Host(cfg, args);

  19:         }

Step 6 – Debug, Run and Install

At this point we are practically done building a Windows Service as well as an application that will run as a Console application.  To show you how simple this is I set a breakpoint in the Start() method of the class.  Pressing F5 to launch the Visual Studio debugger we can see we hit the break point.  This is gold as we didn’t have to do anything we wouldn’t normally do to debug in a Console application.

image

This is the awesome part about Topshelf because we can easily test our service without having to jump through a bunch of hoops.  But here is the best part.  Let’s run it directly from the command prompt and see what happens.

image

That’s it, our application is running and ready to do whatever it programmed to do.  The best part of this is we can now make it a Windows Service by passing a command line argument of “install” to the executable.  When doing this, it will be installed as a Windows Service.  Notice that I am running this command prompt as an Administrator. 

image

Not only did it install our service but it created an EventLog source for the application as well.

If you have to administrate Windows Services for developers you should be really happy right about now.

Let’s open up the services.msc console and find our service.

image

We have a service!

We can easily reverse the install by passing “uninstall” to the executable and the service will be removed from the system. 

But wait there is more that Topshelf can do, stay tuned, we’ll look at that in Part 2.