Reputation: 7350
I have a (Windows only) .NET 8 application and I want to run it as a Windows Service. I want my application to be able to install itself as a service when run from the console. How do I do it?
After this tldr; a bit of context.
With good 'ol .NET Framework, we had InstallUtil.exe, and the corresponding System.Configuration.Install classes (ServiceInstaller) used to run the installation / uninstall by yourself. This was nice and easy.
Enter modern .NET, and a service could now be a daemon on other systems. Microsoft now recommends to build Windows Services with the BackgroundService
infrastructure, and use a very nice and easy service installer (which I don't want to use, because my software is not installed that way), with plenty of tutorials on how to run a wizard to build an external installer (like https://learn.microsoft.com/en-us/dotnet/core/extensions/windows-service-with-installer?tabs=wix). This is not a solution, for me, because I want my software to run (as it is already doing) as both a Console and a Service application.
And, I want to initially run the application as a console app during initial configuration, and later install as a service after the initial configuration.
I used to use the excellent TopShelf
Open Source library (https://github.com/Topshelf/Topshelf) which would allow me to host, install and uninstall the service inside my own process, but the project has been abandoned recently.
I could use PowerShell's New-Service
or sc.exe
and hack my way for the main configurations, but this is for corporate environments and I need a robust and stable implementation: PowerShell is slowly updating and every now and then breaks some argument combination previously working, while sc.exe is obviously stable, but the old command line management is tricky to get right.
I'm thinking I'm going to need to fork TopShelf and extract the installation/uninstallation bits, but I would like spending my time in other activities.
Any ideas?
Upvotes: 0
Views: 239
Reputation: 39916
Even after trying various options, I use two batch files as follow.
Install.bat
sc create MyService binpath= c:\MyService\MyService.exe start=auto
sc start MyService
Uninstall.bat
sc stop MyService
sc delete MyService
I use this in build script.
What you can do is issue similar commands using Process.Start
for sc
and pass remaining arguments for install, uninstall.
Process.Start("sc", new string[] {
"create",
"MyService",
"binpath=" + selfPath,
"start=auto"
});
Upvotes: 0