banner



How To Keep Windows Service Running C# Topshelf

Windows services are programs that are automatically started when the system starts up, or when the user logs in. They run in the background and tin run with a unlike account than the logged-in user. .Cyberspace makes it easy to create Windows services or Linux daemons equally shown in this article.

Services for Windows

Intro

Instead of creating Windows services and Linux daemons, nowadays you might remember about using Docker instead. Docker orchestrators can be used to monitor and scale containers. Before creating a Windows service, you might remember about this alternative. Withal, in that location are even so many scenarios where Windows services are of nifty use.

What are some of the scenarios where Windows services are used? Looking at the services running with Windows, (start the Services app), services to update applications and the operating system (e.g. Windows Update, Microsoft Edge Update Service, Mozilla Maintenance Service, Google Update Service, AdobeUpdateService), services to store credentials for users and applications (Credential Manager), services to offering geolocation information for applications (Geolocation Service), malware checkers (Microsoft Defender Antivirus Service), services to deliver sensor information (Sensor Service), and many more than. Not every of these services is implemented as a separate application – some of the services use the same executable. Looking at the properties of a service you can check the path for the executable including its command-line arguments. Many services that are office of Windows brand use of the svchost.exe, the Geolocation service invokes this with the -k netsvcs -p options.

Windows Services

Services tin be configured to automatically start when the operating organization starts upwardly (startup type Automated). The Automatic Delayed start option allows the user to login before the service is started. Delayed started services are started after the Automated started service. With the Manual configuration, the service starts up based on an consequence – e.thousand. a domain is joined, a firewall port is opened, a group policy is changed, or a custom issue based on Event Tracing for Windows (ETW) is fired.

Create a Worker

Let's start creating a Windows service by creating a background worker. With .NET 6, a groundwork worker can exist created using Visual Studio or the dotnet CLI command dotnet new worker.

The top-level statements created with this application utilize the Host class. The method CreateDefaultBuilder contains functionality to setup the dependency injection container, configuration, and logging. The dependency injection container managed by the Host class is configured by invoking the method ConfigureServices. In the generated lawmaking, the extension method AddHostedService is used to register a background class that implements the interface IHostedService. This interface is indirectly implemented by the Worker grade by deriving from the base of operations course BackgroundService. The interface IHostedService defines the methods StartAsync and StopAsync. Calculation a hosted service, invoking the Run method of the host starts the host and in turn invokes the startup of the IHostedService.

Worker Service - Host configuration

The Worker course derives from the class BackgroundService. BackgroundService implements the interface IHostedService and defines the abstruse method ExecuteAsync. This abstract method is chosen past the StartAsync method in the BackgroundService. StartAsync is defined by the IHostedService interface. With the implementation of the Worker class, ExecuteAsync uses an endless loop (until cancellation is requested) and writes a log message once a second.

Worker

The main functionality for the Host class is creating the dependency injection container, configuration, and logging. Using CreateDefaultBuilder, configuration is read from the configuration files appsettings.json, appsettings.{env.EnvironmentName}.json, environmental variables, and the command line.

Logging configuration is read from the section Logging within the configuration settings. Using the worker template, the configuration file appsettings.json defines logging based on the log level. The default configuration is set to Information:

Logging configuration

If the application runs on a Windows system, the method CreateDefaultBuilder besides adds logging to the Windows issue log and sets a filter provider to merely log warnings and more critical problems to this provider.

Running the application, log information is written to the panel. The worker writes a message every second.

          info: SimpleWorkerService.Worker[0]       Worker running at: 03/17/2022 10:45:55 +01:00 info: SimpleWorkerService.Worker[0]       Worker running at: 03/17/2022 10:45:56 +01:00 info: SimpleWorkerService.Worker[0]       Worker running at: 03/17/2022 ten:45:57 +01:00 info: SimpleWorkerService.Worker[0]       Worker running at: 03/17/2022 x:45:58 +01:00 info: SimpleWorkerService.Worker[0]       Worker running at: 03/17/2022 x:45:59 +01:00                  

Convert to a Windows Service

To build a Windows Service, y'all merely demand to add the NuGet package Microsoft.Extensions.Hosting.WindowsServices, and add together the method invocation UseWindowsService to the IHostBuilder fluent API:

DI Config

To see information level logging in the Windows event log, the filter is explicitly practical with the ConfigureLogging method used with the host builder. The UseWindowsService method configures the source proper name the aforementioned as the application proper name. This information is overwritten configuring the EventLogSettings. In addition to setting the SourceName property of the EventLogSettings, the LogName is set up which creates a split category for logging shown in the Event Viewer.

Because the EventLogLoggerProvider and the EventLogSettings classes are but available on Windows, the OperatingSystem class is used to cheque if the application is running on Windows earlier this API is invoked. In instance your application is not used to run on Linux, you can use the SupportedOSPlatform attribute instead. You tin too specify <TargetPlatform> and specify a Windows Target Framework Moniker.

Installing and Managing the Windows Service

Afterwards building the awarding, the new Windows Service can be published using dotnet publish (or by using Visual Studio):

          dotnet publish -c Release -o c:\sampleservice                  

To control Windows Services, the sc command can be used. Creating a new Windows Service is washed using sc create passing the name of the service and the binPath parameter referencing the executable. This command requires administrator rights:

          sc create "Sample Service" binPath= c:\sampleservice\SimpleWorkerService.exe                  

Using sc create, yous can configure the account with which the service should run (the default is LocalSystem), services which are required to be started before this service (depend), and more than.

The status of the service tin be queried using the Services MMC, or with the command line sc query:

          sc query "Sample Service"                  

After the service is created, it is stopped and need to exist started:

          sc start "Sample Service"                  

To end and delete the service, the sc stop and sc delete commands can be used.

After starting the service, log information can be seen with the Windows Event Viewer. Because the LogName property was set, in that location'southward a dissever category with Awarding and Services Logs:

Windows Event Viewer Log

Passing Arguments

With a Windows Service, it'due south possible to pass command-line arguments with the service configuration. To read the arguments, the Environment class tin can be used every bit shown in the post-obit code snippet.

Reading Command-Line Arguments

When creating the service using sc create, pay attention to get out a blank afterward the binPath option. You can supply the parameters within the quotes:

          sc create "Sample Service" binPath= "c:\sampleservice\SimpleWorkerService.exe --p1=one --p2=two"                  

Web Application as Windows Service

What about hosting Kestrel as a Windows Service? In that location'due south non a lot difference using the packet Microsoft.Extensions.Hosting.WindowsServices – in principle but the API UseWindowsService needs to be invoked. Allow'southward get into details using the .NET 6 WebApplicationBuilder class.

A Spider web API projection can exist created using dotnet new webapi. This template creates an API returning random weather information. With the option –use-minimal-apis, controllers are not used, and the consummate functionality of the API can be defined with top-level statements. The parameter –no-https specifies to create an implementation with HTTP. Using HTTPS, information technology's necessary to create and configure a certificate that'due south used by the account running the service. Depending on the scenario how you employ this Windows service, HTTP tin can be ok.

          dotnet new webapi --use-minimal-apis --no-https -o ASPNETCoreWindowsService                  

The UseWindowsService method is an extension method for IHostBuilder. With .Cyberspace six, WebApplication and WebApplicationBuilder are used instead of the Host and HostBuilder classes. Of course, you can also change the lawmaking to the old .NET five version. WebApplication offers an abstraction layer of the Host class and makes information technology easier to configure ASP.NET Core middleware. With .Internet five, the Startup class has been used. Instead of using the Startup course now everything tin can be done with top-level statements. The Minimal API makes use of C# ten features and adds some APIs, e.1000. a new overload of the MapGet method. Using the WebApplicationBuilder class, the functionality of the IHostBuilder tin can be accessed using the Host property. This property returns a ConfigureHostBuilder example which implements the interface IHostBuilder. Hither y'all can use the extension method UseWindowsService similar before. The UseWindowsService extension method configures the content root path to AppContext.BaseDirectory for the Windows service. Because the CreateBuilder method already needs this directory, this directory needs to be specified with the WebApplicationOptions as shown. To specify a log category with the Windows event logs, the EventLogSettings are configured as before with the console application:

Windows Services with ASP.NET Core

The Kestrel server can be configured accessing the WebHost belongings of the WebApplicationBuilder, invoking the method ConfigureKestrel. With the sample application, the Kestrel server is configured using appsettings.json:

Kestrel Configuration

Now the service tin can be build, published, and configured as a Windows Service in the same fashion as mentioned before using the worker application. Opening a browser to reference the configured port with the controller route WeatherForecast returns JSON information from the API service:

http://localhost:9200/weatherforecast

Weather Forecast

Accessing the Windows Service from a different system, the Firewall needs to be configured to let accessing this port from the exterior.

Linux Daemons

What about running this application on Linux? The method UseWindowsService checks if it's running on Windows every bit a Windows service, and returns if this is not the case. With this you tin can run the application on the Linux system too. To create a Linux daemon, y'all tin can add the NuGet package Microsoft.Extensions.Hosting.Systemd, and invoke the method UseSystemd. What's dissimilar is the configuration of systemd. To use systemd with WSL-two, yous tin use Distrod to run your Ubuntu environs. See a link below for Distrod.

Take away

Starting with .Internet iii, the Host course was introduced which abstracts configuration for logging, dependency injecction, and configuration in 1 identify. Extension methods arrive easy to offer more features. With this, using the NuGet parcel Microsoft.Extensions.Hosting.WindowsServices just one API method is required to create a Windows Service. This way, background functionalty based on the worker template, just also hosting a Kestrel server for offering ASP.Cyberspace Core Web applications and services is an easy chore.

If y'all like this article, it would exist cracking if you buy a coffee:

How To Keep Windows Service Running C# Topshelf,

Source: https://csharp.christiannagel.com/2022/03/22/windowsservice-2/

Posted by: morriscouttepore1968.blogspot.com

0 Response to "How To Keep Windows Service Running C# Topshelf"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel