Create a windows service in .net using Topshelf

In the previous post, we have discussed how to create a windows service using the .net with visual studio project template. In this post,  we will see creating a windows service using the Topshelf library. Also, We would discuss the advantage of using Topshelf over using visual studio project template.

Windows Service with Topshelf

Objectives:

  • Why Topshelf.
  • Creating windows service using Topshelf
  • Installation/Uninstallation
  • Source code

Topshelf is an open source framework library that helps to host the windows services developed in .net. Topshelf library helps the developer in multiple ways, right from the development, debugging to the installation of the product.

Why Topshelf:

1.   Easy Development:

Using Topshelf, a console application can be hosted as windows service. It is always easy to create a console app than creating a windows service using visual studio project template.

2.   Easy Debugging:

Windows service created using Topshelf can be debugged as easy as a console app. We can debug the code just by pressing F5 and F10 as usual. You do not need to install windows service and attach the running process as needed by when we create windows service using a project template. You can refer the debugging process for windows service in my previous post.

3.   Easy Installation: 

You do not need to know about “InstallUtil.exe” and its related dependency and commands. With Topshelf we just need a simple command ‘Product.exe install‘ and for uninstallation ‘Product.exe uninstall’

4. Nuget Presence:

It can be added in the project as the Nuget library.

 

Creating windows service in .net using Topshelf

Below are the steps to be followed:

1. Create new project -> Select Console application.

Console application

2. Add Topshelf nuget library into your project.

  • RightClick  on your project
  • Choose “Manage NuGet Packages”
  • Search Topshelf in the NuGet Package window.
  • Click “Install”

Topshelf nuget

3. Add a class that contains the windows service logic such as what should be done on service start and service stopped.

Here, Class should contain 2 methods Start() and Stop() which will be wired up with the OnStart and OnStop events of windows service respectively. These methods are not mandatory to define and wired up. Below class log the message to a log file on start and stop events.

using System;
using System.IO;

namespace WinServiceTopShelf
{
    public class OwnService
    {        
        public void Start()
        {
            WriteToFile("Service started. Timestamp " + DateTime.Now);           
        }
        public void Stop()
        {
            WriteToFile("Service stopped. Timestamp " + DateTime.Now);
        }
       
        public void WriteToFile(string Message)
        {
            string path = AppDomain.CurrentDomain.BaseDirectory + "\\LocalLog";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            string filepath = AppDomain.CurrentDomain.BaseDirectory + "\\LocalLog\\Log_" + DateTime.Now.Date.ToShortDateString().Replace('/', '_') + ".txt";
            if (!File.Exists(filepath))
            {
                // Create a file to write to.   
                using (StreamWriter sw = File.CreateText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
            else
            {
                using (StreamWriter sw = File.AppendText(filepath))
                {
                    sw.WriteLine(Message);
                }
            }
        }
    }
}

4. Create a configuration file which has Topshelf configuration related to service information such as ServiceName, ServiceDescription and EventBinding[start and stop] etc.

using Topshelf;

namespace WinServiceTopShelf
{
    internal class Configuration
    {
        internal static void Configure()
        {
            HostFactory.Run(configure =>
            {
                configure.Service(service =>
                {
                    service.ConstructUsing(s => new OwnService());
                    service.WhenStarted(s => s.Start());
                    service.WhenStopped(s => s.Stop());
                });
                //Setup Account that window service use to run.  
                configure.RunAsLocalSystem();
                configure.SetServiceName("WinServiceWithTopshelf");
                configure.SetDisplayName("WinServiceWithTopshelf");
                configure.SetDescription("WinService With Topshelf");
            });
        }
    }
}

5. Now, In program.cs file, call the Configure() method.

public class Program
    {
        static void Main(string[] args)
        {
            Configuration.Configure();
        }
    }

6. Now window service is created. You can run this service by clicking Start button or pressing F5. 

Installation/Uninstallation:

  1. Run CMD as administrator
  2. Set drive path to bin/debug folder where application.exe exists.
  3. execute this command for installation: <application>.exe install
  4. execute this command for Un-installation: <application>.exe uninstall

Sourcecode:

WinServiceSourceCode

 

Conclusion:

In this post, We have seen the advantage of using topshelf for hosting the windows service developed in .net. Happy coding.

admin

Software professional, Blogger, Tech enthusiast.