Application setup

Add the latest NuGet package Microsoft.Extensions.Hosting.WindowsServices.

Install-Package Microsoft.Extensions.Hosting.WindowsServices
or
dotnet add package Microsoft.Extensions.Hosting.WindowsServices

In program.cs we need to call the UseWindowsServices() method on webBuilder.

public static IHostBuilder CreateHostBuilder(string[] args) =>
				Host.CreateDefaultBuilder(args)
						.ConfigureWebHostDefaults(webBuilder => {
							webBuilder.UseStartup<Startup>()
							.UseKestrel(opt => opt.ListenAnyIP(1337));
						})
						.UseWindowsService(); // <-- add this

Because a windows service always returns C:\Windows\system32 as it’s base path, things like paths to configs and wwwroot will not be correct, and this can be mitigated by telling the service where it lives based on the main process like below. (note this is for SelfContained publish)

...				
.UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)) // <-- add this
.UseWindowsService()
...

Windows service setup

Open an elevated cmd window (not powershell) to run the following commands.

Install service

Note that the name may NOT contain spaces!
And leave a space after binPath= as below.

sc create <service-name> binPath= "<full-path-to-exe>"

# Example:
sc create MyService binPath= "C:\Services\MyService.exe"

Delete service

sc delete <service-name>

# Example:
sc delete MyService

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.