How to make a Windows Service from .NET Core 2.1/2.2

前端 未结 3 1411
攒了一身酷
攒了一身酷 2020-12-30 04:31

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

3条回答
  •  长情又很酷
    2020-12-30 05:03

    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:

    • Append UseWindowsService() to the HostBuilder. This will also configure your application to use the EventLog logger.
    • Change the SDK in your project to Microsoft.NET.Sdk.Worker ().
    • Make sure that the output project type is EXE file (Exe)
    • Append 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.

    .csproj file:

    
    
      
        Exe
        win7-x64
        netcoreapp2.1
      
    
      
        
      
    
    
    

    File Program.cs:

    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    
    namespace NetcoreWindowsService
    {
        class Program
        {
            static void Main()
            {
                new HostBuilder()
                    .ConfigureServices(services => services.AddHostedService())
                    .UseWindowsService()
                    .Build()
                    .Run();
            }
        }
    }
    

    File MyService.cs:

    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;
            }
        }
    }
    

提交回复
热议问题