Thursday, December 13, 2018

Building .Net Core Windows Services

In this post I will describe the steps required to set up a .Net Core 2.2 process as a Windows Service.
When .Net Core was released, it promised a trimmed down list of API support from its predecessor, .Net Framework.  The result is multiple platform support and performance.

There were a number of handy APIs that were dropped however, Windows service hosting being one of them.  As I have no requirement for Linux, I could look for a solution that was Windows-specific.
A bit of digging turned up some posts from Steve Gordon (thanks!), in particular where he presents the Microsoft.Extensions.Hosting package and Windows hosting ( click here for post and here for his github sample ).

With no further ado, here are the steps required:
  • First create a .Net Core console application.
  • Set the language version to at least 7.1 to support async Task for the Main method.  (Access the language version from the project settings->Build->Advanced->Language Settings.
  • Add the Microsoft.Extensions.Hosting and the System.ServiceProcess.ServiceController packages.
  • Edit the project .csproj file and include in the PropertyGroup: <RuntimeIdentifier>win7-x64</RuntimeIdentifier>
  • Insure you have in the PropertyGroup  <OutputType>Exe</OutputType>
Now go to Program.cs and copy the following:
This code will support interactive debugging and production execution, and runs the example class LoggingService.


Here is a skeleton example of the service itself: The final two files necessary to complete the project: In order to install, run or delete the service I use the 'sc' utility:
sc create AdvancedHost binPath="C:\temp\AdvancedHost\AdvancedHost.exe"
where 'AdvancedHost' is the service name and the value for binPath is the compiled executable.

Once the service is created, to start:
sc start AdvancedHost

To stop:
sc stop AdvancedHost

and finally to delete (once stopped):
sc delete AdvancedHost

There are many more features contained in sc; just type 'sc' alone on the command line.
The results of sc can be seen in the services Windows control panel.

No comments:

Post a Comment

Building .Net Core Windows Services

In this post I will describe the steps required to set up a .Net Core 2.2 process as a Windows Service. When .Net Core was released, it pro...