.Net Core Worker Service
Worker services are background services that may sometimes be required to perform a business operation, such as monitoring a service, resources, DB, etc. .Net Core worker service can run in different OS like Windows, Linux, etc. Personally, I have used it to download a file from the internet, then parse it and store it in the database. And one more thing to note is that it will not have a UI.
Let's start with the demo:
a. Create a project and select the 'Worker Service' template.
c. The method to note is ExecuteAsync in a worker.cs file
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
The code is simple to understand: it logs the current time for every 1 second. This is where we need to add our business logic.
d. When we debug this, we may see a command prompt. However, when we install this service, we don't see a prompt window. Hence, we will not see the logs too since we don't have a window. So, we shall write logs to a text file. To add logs to a text file, we need to configure Serilog.
e. To add Serilog (this is a basic Serilog feature), add Serilog.AspNetCore and Serilog.Sinks.File NuGetPackages.
f. Next, in the Main function add the below code
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft",Serilog.Events.LogEventLevel.Warning)
.Enrich.FromLogContext()
.WriteTo.File(@"C:\a\test.txt")
.CreateLogger();
h. Modify public static IHostBuilder CreateHostBuilder(string[] args as below
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
})
.UseSerilog(); // add this
I. That's it! When you run the application, we will see the log created at C:\a\test.txt
k. This worker service can be installed on multiple platforms: Windows, Linux, Mac. Let us see how we can install it on the Windows platform.l. Our service executable is ready; now we need to install it on our machine. To install it on our machine, we need to use sc.exe. Run following command in Powershell.
n. Right-click on the MyService and start the service. Next, check the log files. You would notice that the log file is getting created, and the log is being written.