.Net Core Worker Service

 


.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.



b. Provide a name for the service and select default values.

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.

To install it in the windows platform, we need to install the below package: Microsoft.Extensions.Hosting.WindowsServices



l. Next to configure our service as a WIndows service, we have to add UseWindowsService() in  public static IHostBuilder CreateHostBuilder(string[] args) as below:

    public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
            .UseWindowsService()
                .ConfigureServices((hostContext, services) =>
                {
                    services.AddHostedService<Worker>();
                })
            .UseSerilog();

j. Next, let us publish it to create a service exe. To publish, right-click on the solution, and click Publish. Click on Start and Click Folder. Select the folder you need to save the binaries, i.e., dlls and exes.




k. Once you are done with the publishing, we would see the binaries as below:


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.

sc.exe create MyServiceName binpath=C:\a\workerService\WorkerServiceDemo.exe start=auto

m. Service will be installed in the machine. Open Services.msc, you would find this service here:


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.

Writing a log file is just simple business logic. However, we usually add complex logic, such as monitoring something(DB, service). 

The code is shared here - https://github.com/bharath9788/WorkerServiceDemo

Happy Coding!