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 thisBecause 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
Hi, my name is Niels, I am a passionate software developer from Denmark with a love for coding and solving real-world problems! I taught myself C# back in 2012 in my spare time and I loved it! I went on and graduated from Computer Science in 2016 where I got hired by