In a previous version of a Professional C# book I’ve written a complete chapter on how to create Windows Services with the .NET Framework. Using .NET Core 3.0, it’s a lot easier to create Windows Services: just a single line of code is needed to convert a background worker to a Windows Service.
With .NET Core 3.0, a background worker can be created using Visual Studio or the dotnet CLI command dotnet new worker.
With this template, a Program
class is created that uses the Host
class. The method CreateDefaultBuilder
is used 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 code, the extension method AddHostedService
is used to register a background class that implements the interface IHostedService
. This interface is indirectly implemented by the Worker
class by deriving from the base class BackgroundService
. The interface IHostedService
defines the methods StartAsync
and StopAsync
. Adding a hosted service, invoking the Run
method of the host starts the host and in turn invokes the startup of the IHostedService
.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
**public**
**class**
Program
{
**public**
**static**
**void**
Main(``**string**``[] args)
{
CreateHostBuilder(args).Build().Run();
}
**public**
**static**
IHostBuilder CreateHostBuilder(``**string**``[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>()
.Configure<EventLogSettings>(config =>
{
config.LogName =
"Sample Service"``;
config.SourceName =
"Sample Service Source"``;
});
});
}
The
_Host_
class is also used by ASP.NET Core 3.0 Web projects. The_WebHost_
class from .NET Core 2.0 is replaced by the more generic_Host_
class.
The Worker
class derives from the class BackgroundService
. BackgroundService
implements the interface IHostedService
and defines the abstract method ExecuteAsync
. This abstract method is called by 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.
#.net core #asp.net core #aspnetcore #dotnetcore #windows service