Cross-platform background service in .NET Core (think windows service/unix daemon)? Cross-platform background service in .NET Core (think windows service/unix daemon)? unix unix

Cross-platform background service in .NET Core (think windows service/unix daemon)?


Windows service by itself is a console application which conforms to the interface rules and protocols of the Windows Service Control Manager. You can achieve the same on both platforms using .net core console application as a host.It will require to do some extra configuration to make it behave more like a real service / daemon.

Linux

E.g. for Linux you can use SystemD.You need to create a SystemD configuration file with something like this first:

[Unit]Description=daemon serviceAfter=network.target[Service]ExecStart=/usr/bin/dotnet $(pwd)/bin/daemonsrv.dll 10000Restart=on-failure[Install]WantedBy=multi-user.targetEOF

And then configure SystemD to make it aware of your service configuration

# Copy service file to a System locationsudo cp daemonsrv.service /lib/systemd/system# Reload SystemD and enable the service, so it will restart on rebootssudo systemctl daemon-reload sudo systemctl enable daemonsrv# Start servicesudo systemctl start daemonsrv# View service statussystemctl status daemonsrv

Windows

For windows you should do mostly the same but with a different toolset. You will have to use a third party service manager to avoid a tight windows binding.E.g. you can use NSSM. And here is the nice article with examples about it - .Net Core console application as a Windows Service.

Btw you can still use a normal windows service setup just as a host in a case of a Windows. And write another host for you Unix environments (console app host). Both of them can share the business logic and only the way they react to system events will differ.

Hope it helps.


See Worker Services (.NET Core 3.x):

You can create one from the new Visual Studio 2019 Worker Service project template, or by using the .NET CLI:

dotnet new worker

See also:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studio