Skip to content

Creating a dotnet core windows service

Services are great for performing reoccurring tasks, especially if the task needs to be repeated often, say every minute. They also have the benefit of not requiring anyone to be logged in to run the service.

Luckily with dot net core, you can have one set up and running very easily with the help of TopShelf. To get started, create a new console application using the CLI.

dotnet new console --name MyService

Import the TopShelf NuGet into your .csproj file like so

<ItemGroup>
    <PackageReference Include="Topshelf" Version="4.2.1" />
</ItemGroup>

In your program file, configure and run a new service host. In the example below I create my new service “Processor”, enable it to recover on failure; restarting after 10 seconds, give it a name, and tell it to start automatically.

class Program
{
    static void Main(string[] args) => HostFactory.Run(x =>
    {
       x.Service<Processor>();
       x.EnableServiceRecovery(r => r.RestartService(TimeSpan.FromSeconds(10)));
       x.SetServiceName("MyService");
       x.StartAutomatically();
    });
 }

Then you simply have to create the service. In this case, I have called the main component of this service “Processor”. You should implement ServiceControl and its two methods start and stop. Then using a Timer you can call your root function on a schedule.

public class Processor : ServiceControl
{
   private Timer _timer = new Timer();

   public async Task Process()
   {
      //The start point for whatever task your service is going to do
   }

   public bool Start(HostControl hostControl)
   {
      _timer.Elapsed += new ElapsedEventHandler(async (object source, 
              ElapsedEventArgs e) => await Process());
      _timer.Interval = 60000;

      _timer.Start();
      return true;
   }

   public bool Stop(HostControl hostControl)
   {
      _timer.Stop();
      return true;
   }
}

Deploying and installing your service is then a breeze. The first thing you will need to do is publish the service. You can use the following command to achieve this. Run it from the root of your project. This will produce a publish folder containing an .exe file.

dotnet publish -r win-x64 -c Release

Then you can simply grab the publish folder and copy it to the server you need to install the service on. After you can run the following command from the same folder.

MyService.exe install

This will utilize the TopShelf hooks to install the service onto the machine and start it running. Your service will now be installed and running on the machine.

That’s all there is to it!

Published inC#

Comments are closed.