Home windows providers are packages which are mechanically began when the system begins up, or when the person logs in. They run within the background and may run with a distinct account than the logged-in person. .NET makes it simple to create Home windows providers or Linux daemons as proven on this article.
Intro
As a substitute of making Home windows providers and Linux daemons, these days you would possibly consider using Docker as an alternative. Docker orchestrators can be utilized to observe and scale containers. Earlier than making a Home windows service, you would possibly take into consideration this various. Nonetheless, there are nonetheless many eventualities the place Home windows providers are of nice use.
What are a few of the eventualities the place Home windows providers are used? Trying on the providers operating with Home windows, (begin the Providers app), providers to replace functions and the working system (e.g. Home windows Replace, Microsoft Edge Replace Service, Mozilla Upkeep Service, Google Replace Service, AdobeUpdateService), providers to retailer credentials for customers and functions (Credential Supervisor), providers to supply geolocation data for functions (Geolocation Service), malware checkers (Microsoft Defender Antivirus Service), providers to ship sensor information (Sensor Service), and lots of extra. Not each of those providers is carried out as a separate software – a few of the providers use the identical executable. Trying on the properties of a service you may test the trail for the executable together with its command-line arguments. Many providers which are a part of Home windows make use of the svchost.exe, the Geolocation service invokes this with the -k netsvcs -p choices.
Providers will be configured to mechanically begin when the working system begins up (startup sort Automated). The Automated Delayed begin possibility permits the person to login earlier than the service is began. Delayed began providers are began after the Automated began service. With the Guide configuration, the service begins up based mostly on an occasion – e.g. a site is joined, a firewall port is opened, a gaggle coverage is modified, or a customized occasion based mostly on Occasion Tracing for Home windows (ETW) is fired.
Create a Employee
Let’s begin making a Home windows service by making a background employee. With .NET 6, a background employee will be created utilizing Visible Studio or the dotnet CLI command dotnet new employee.
The highest-level statements created with this software use the Host
class. The strategy CreateDefaultBuilder
comprises performance to setup the dependency injection container, configuration, and logging. The dependency injection container managed by the Host
class is configured by invoking the tactic ConfigureServices
. Within the generated code, the extension methodology AddHostedService
is used to register a background class that implements the interface IHostedService
. This interface is not directly carried out by the Employee
class by deriving from the bottom class BackgroundService
. The interface IHostedService
defines the strategies StartAsync
and StopAsync
. Including a hosted service, invoking the Run
methodology of the host begins the host and in flip invokes the startup of the IHostedService
.
The Employee
class derives from the category BackgroundService
. BackgroundService
implements the interface IHostedService
and defines the summary methodology ExecuteAsync
. This summary methodology is named by the StartAsync
methodology within the BackgroundService
. StartAsync
is outlined by the IHostedService
interface. With the implementation of the Employee
class, ExecuteAsync
makes use of an infinite loop (till cancellation is requested) and writes a log message as soon as a second.
The principle performance for the Host
class is creating the dependency injection container, configuration, and logging. Utilizing CreateDefaultBuilder
, configuration is learn from the configuration information appsettings.json, appsettings.{env.EnvironmentName}.json, environmental variables, and the command line.
Logging configuration is learn from the part Logging inside the configuration settings. Utilizing the employee template, the configuration file appsettings.json defines logging based mostly on the log stage. The default configuration is about to Info:
If the appliance runs on a Home windows system, the tactic CreateDefaultBuilder
additionally provides logging to the Home windows occasion log and units a filter supplier to solely log warnings and extra crucial points to this supplier.
Operating the appliance, log data is written to the console. The employee writes a message each second.
information: SimpleWorkerService.Employee[0]
Employee operating at: 03/17/2022 10:45:55 +01:00
information: SimpleWorkerService.Employee[0]
Employee operating at: 03/17/2022 10:45:56 +01:00
information: SimpleWorkerService.Employee[0]
Employee operating at: 03/17/2022 10:45:57 +01:00
information: SimpleWorkerService.Employee[0]
Employee operating at: 03/17/2022 10:45:58 +01:00
information: SimpleWorkerService.Employee[0]
Employee operating at: 03/17/2022 10:45:59 +01:00
Convert to a Home windows Service
To construct a Home windows Service, you simply want so as to add the NuGet package deal Microsoft.Extensions.Internet hosting.WindowsServices, and add the tactic invocation UseWindowsService
to the IHostBuilder
fluent API:
To see data stage logging within the Home windows occasion log, the filter is explicitly utilized with the ConfigureLogging
methodology used with the host builder. The UseWindowsService
methodology configures the supply identify the identical as the appliance identify. This data is overwritten configuring the EventLogSettings
. Along with setting the SourceName
property of the EventLogSettings
, the LogName
is about which creates a separate class for logging proven within the Occasion Viewer.
As a result of the
EventLogLoggerProvider
and theEventLogSettings
courses are solely obtainable on Home windows, theOperatingSystem
class is used to test if the appliance is operating on Home windows earlier than this API is invoked. In case your software isn’t used to run on Linux, you need to use theSupportedOSPlatform
attribute as an alternative. You can too specify <TargetPlatform> and specify a Home windows Goal Framework Moniker.
Putting in and Managing the Home windows Service
After constructing the appliance, the brand new Home windows Service will be printed utilizing dotnet publish (or through the use of Visible Studio):
dotnet publish -c Launch -o c:sampleservice
To regulate Home windows Providers, the sc command can be utilized. Creating a brand new Home windows Service is finished utilizing sc create passing the identify of the service and the binPath parameter referencing the executable. This command requires administrator rights:
sc create "Pattern Service" binPath= c:sampleserviceSimpleWorkerService.exe
Utilizing sc create, you may configure the account with which the service ought to run (the default is LocalSystem), providers that are required to be began earlier than this service (rely), and extra.
The standing of the service will be queried utilizing the Providers MMC, or with the command line sc question:
sc question "Pattern Service"
After the service is created, it’s stopped and must be began:
sc begin "Pattern Service"
To cease and delete the service, the sc cease and sc delete instructions can be utilized.
After beginning the service, log data will be seen with the Home windows Occasion Viewer. As a result of the LogName
property was set, there’s a separate class with Software and Providers Logs:
Passing Arguments
With a Home windows Service, it’s doable to go command-line arguments with the service configuration. To learn the arguments, the Atmosphere
class can be utilized as proven within the following code snippet.
When creating the service utilizing sc create, take note of depart a clean after the binPath possibility. You’ll be able to provide the parameters inside the quotes:
sc create "Pattern Service" binPath= "c:sampleserviceSimpleWorkerService.exe --p1=one --p2=two"
Internet Software as Home windows Service
What about internet hosting Kestrel as a Home windows Service? There’s not so much distinction utilizing the package deal Microsoft.Extensions.Internet hosting.WindowsServices – in precept simply the API UseWindowsService must be invoked. Let’s get into particulars utilizing the .NET 6 WebApplicationBuilder
class.
A Internet API undertaking will be created utilizing dotnet new webapi. This template creates an API returning random climate data. With the choice –use-minimal-apis, controllers will not be used, and the entire performance of the API will be outlined with top-level statements. The parameter –no-https specifies to create an implementation with HTTP. Utilizing HTTPS, it’s essential to create and configure a certificates that’s utilized by the account operating the service. Relying on the state of affairs how you employ this Home windows service, HTTP will be okay.
dotnet new webapi --use-minimal-apis --no-https -o ASPNETCoreWindowsService
The UseWindowsService
methodology is an extension methodology for IHostBuilder
. With .NET 6, WebApplication
and WebApplicationBuilder
are used as an alternative of the Host
and HostBuilder
courses. After all, it’s also possible to change the code to the outdated .NET 5 model. WebApplication
provides an abstraction layer of the Host
class and makes it simpler to configure ASP.NET Core middleware. With .NET 5, the Startup
class has been used. As a substitute of utilizing the Startup
class now all the things will be completed with top-level statements. The Minimal API makes use of C# 10 options and provides some APIs, e.g. a brand new overload of the MapGet
methodology. Utilizing the WebApplicationBuilder
class, the performance of the IHostBuilder
will be accessed utilizing the Host
property. This property returns a ConfigureHostBuilder
occasion which implements the interface IHostBuilder
. Right here you need to use the extension methodology UseWindowsService
like earlier than. The UseWindowsService
extension methodology configures the content material root path to AppContext.BaseDirectory
for the Home windows service. As a result of the CreateBuilder
methodology already wants this listing, this listing must be specified with the WebApplicationOptions
as proven. To specify a log class with the Home windows occasion logs, the EventLogSettings
are configured as earlier than with the console software:
The Kestrel server will be configured accessing the WebHost
property of the WebApplicationBuilder
, invoking the tactic ConfigureKestrel
. With the pattern software, the Kestrel server is configured utilizing appsettings.json:
Now the service will be construct, printed, and configured as a Home windows Service in the identical means as talked about earlier than utilizing the employee software. Opening a browser to reference the configured port with the controller route WeatherForecast returns JSON data from the API service:
http://localhost:9200/weatherforecast
Accessing the Home windows Service from a distinct system, the Firewall must be configured to permit accessing this port from the surface.
Linux Daemons
What about operating this software on Linux? The strategy UseWindowsService
checks if it’s operating on Home windows as a Home windows service, and returns if this isn’t the case. With this you may run the appliance on the Linux system as effectively. To create a Linux daemon, you may add the NuGet package deal Microsoft.Extensions.Internet hosting.Systemd, and invoke the tactic UseSystemd
. What’s totally different is the configuration of systemd. To make use of systemd with WSL-2, you need to use Distrod to run your Ubuntu atmosphere. See a hyperlink beneath for Distrod.
Take away
Beginning with .NET 3, the Host
class was launched which abstracts configuration for logging, dependency injecction, and configuration in a single place. Extension strategies make it simple to supply extra options. With this, utilizing the NuGet package deal Microsoft.Extensions.Internet hosting.WindowsServices only one API methodology is required to create a Home windows Service. This fashion, background functionalty based mostly on the employee template, but in addition internet hosting a Kestrel server for providing ASP.NET Core Internet functions and providers is a straightforward process.
For those who like this text, it could be nice if you happen to purchase a espresso: