Recently I had a need to convert a .NET Core 2.1 or 2.2 console application into a Windows Service.
As I didn\'t have a requirement to port this process to Linux, I c
You no longer need to copy-paste a lot of code to do it. All you need is to install the package Microsoft.Extensions.Hosting.WindowsServices
Then:
UseWindowsService() to the HostBuilder. This will also configure your application to use the EventLog logger.Microsoft.NET.Sdk.Worker ().Exe )win7-x64 to the project file.Debug your service like a regular console application, and then run dotnet publish, sc create ..., etc.
That's it. This also works for .NET Core 3.0/3.1. Read more here.
The minimal code example is shown below.
Exe
win7-x64
netcoreapp2.1
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace NetcoreWindowsService
{
class Program
{
static void Main()
{
new HostBuilder()
.ConfigureServices(services => services.AddHostedService())
.UseWindowsService()
.Build()
.Run();
}
}
}
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System.Threading;
using System.Threading.Tasks;
namespace NetcoreWindowsService
{
internal class MyService : IHostedService
{
private readonly ILogger _logger;
public MyService(ILogger logger) => _logger = logger;
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("The service has been started");
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("The service has been stopped");
return Task.CompletedTask;
}
}
}