Create a .NET Windows Service in 5 steps with Topshelf

Source: Christoph De Baene

Topshelf is an open-source hosting framework for building Windows Services using .NET. With Topshelf you can create in a few lines of code your own windows service. It’s a kind of internal DSL for building windows services. I used version 2.2 of Topshelf and the binaries and sources can be found here (GitHub).

First download Topshelf from GitHub, I used version 2.2 (direct link).

  1. Create a console application named ‘SampleWindowsService‘ inside Visual Studio
    [message type="info"]Be sure to change the target framework to ‘.NET Framework 4‘[/message]
  2. Reference the binaries TopShelf.dll and log4net.dll (included in Topshelf).
  3. Create a simple service called ‘SampleService’ that simply write every 5 seconds to the log. Note that we create explicit a Start and Stop method which is conceptually the minimum that a windows service need.[csharp]<br /> public class SampleService<br /> {<br /> private Timer _timer = null;<br /> readonly ILog _log = LogManager.GetLogger(<br /> typeof(SampleService));</p> <p> public SampleService()<br /> {<br /> double interval = 5000;<br /> _timer = new Timer(interval);<br /> _timer.Elapsed += new ElapsedEventHandler(OnTick);<br /> }</p> <p> protected virtual void OnTick(object sender, ElapsedEventArgs e)<br /> {<br /> _log.Debug(&quot;Tick:&quot; + DateTime.Now.ToLongTimeString());<br /> }</p> <p> public void Start()<br /> {<br /> _log.Info(&quot;SampleService is Started&quot;);</p> <p> _timer.AutoReset = true;<br /> _timer.Enabled = true;<br /> _timer.Start();<br /> }</p> <p> public void Stop()<br /> {<br /> _log.Info(&quot;SampleService is Stopped&quot;);</p> <p> _timer.AutoReset = false;<br /> _timer.Enabled = false;<br /> }<br /> }<br /> [/csharp]
  4. In the main method of our console application we will use Topshelf to host our SampleService.
    We we are telling Topshelf how to start and stop the service, what the service name is, etc.
    Note that we need to configure log4net for Topshelf and our service![csharp]<br /> static void Main(string[] args)<br /> {<br /> XmlConfigurator.ConfigureAndWatch(<br /> new FileInfo(&quot;.\log4net.config&quot;));</p> <p> var host = HostFactory.New(x =&gt;<br /> {<br /> x.EnableDashboard();<br /> x.Service(s =&gt;<br /> {<br /> s.SetServiceName(&quot;SampleService&quot;);<br /> s.ConstructUsing(name =&gt; new SampleService());<br /> s.WhenStarted(tc =&gt;<br /> {<br /> XmlConfigurator.ConfigureAndWatch(<br /> new FileInfo(&quot;.\log4net.config&quot;));<br /> tc.Start();<br /> });<br /> s.WhenStopped(tc =&gt; tc.Stop());<br /> });</p> <p> x.RunAsLocalSystem();<br /> x.SetDescription(&quot;SampleService Description&quot;);<br /> x.SetDisplayName(&quot;SampleService&quot;);<br /> x.SetServiceName(&quot;SampleService&quot;);<br /> });</p> <p> host.Run();<br /> }<br /> [/csharp]
  5. The only thing we have to do now is to configure log4net. Create a file called ‘log4net.config‘ with the following configuration.[xml]<br /> &lt;!&#8211;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; ?&#8211;&gt;</p> <p>[/xml]

    This configuration enables to output to the console and through a UDP network protocol so that we can easily monitor the log statements when installed as a windows service. I used Log2Console (Codeplex) to monitor my log statements through UDP.
    [message type="info"]Make sure the output directory of log4net.config is set to ‘Copy always’[/message] [message type="warning"]Note that there is an issue with log4net related to IPv6 and Windows Vista/7. You can fix it by adding the following ’127.0.0.1 log4view-local’ to your hosts file which can be found in folder C:WindowsSystem32driversetchosts.[/message]

When you fit F5 you will see that Topshelf outputs some log statements and you will see that the log statements of our SampleService is included and everything is working properly.

In order to install SampleService as a Windows Service you simply need to do the following through the command prompt.

[message type="info"]Be sure to launch the command prompt as an administrator![/message]

[text]SampleWindowsService.exe install[/text]

After that when the windows service has been installed successfully we can start the service through services.msc or simply by typing

[text]SampleWindowsService.exe start[/text]

Now we can open Log2Console to monitor our log files that is send through the UDP appender.


To uninstall the service we simply write

[text]SampleWindowsService.exe uninstall[/text]

The sources can be found here (BitBucket)

Christoph De Baene, one of our experts, regularly blogs at Christoph De Baene.

Posted in Microsoft | Tagged , | Comments Off

Comments are closed.