Writing windows service in .net core

前端 未结 3 821
太阳男子
太阳男子 2021-01-13 10:53

My question is How can I write the windows service in .net core which we used to write in prior .net versions ?

Lots of links/articles explain how to host your .net

3条回答
  •  礼貌的吻别
    2021-01-13 11:32

    This is another simple way to build windows service in .net Core (console app)

    DotNetCore.WindowsService

    Simple library that allows one to host dot net core application as windows services.

    Installation

    Using nuget: Install-Package PeterKottas.DotNetCore.WindowsService

    Usage

    1. Create .NETCore console app.
    2. Create your first service, something like this:

      public class ExampleService : IMicroService
      {
          public void Start()
          {
              Console.WriteLine("I started");
          }
      
          public void Stop()
          {
              Console.WriteLine("I stopped");
          }
      }  
      
    3. Api for services:

      ServiceRunner.Run(config =>
      {
          var name = config.GetDefaultName();
          config.Service(serviceConfig =>
          {
              serviceConfig.ServiceFactory((extraArguments) =>
          {
              return new ExampleService();
          });
          serviceConfig.OnStart((service, extraArguments) =>
          {
              Console.WriteLine("Service {0} started", name);
              service.Start();
          });
      
          serviceConfig.OnStop(service =>
          {
              Console.WriteLine("Service {0} stopped", name);
              service.Stop();
          });
      
          serviceConfig.OnError(e =>
          {
              Console.WriteLine("Service {0} errored with exception : {1}", name, e.Message);});
          });
      });
      
    4. Run the service without arguments and it runs like console app.

    5. Run the service with action:install and it will install the service.
    6. Run the service with action:uninstall and it will uninstall the service.
    7. Run the service with action:start and it will start the service.
    8. Run the service with action:stop and it will stop the service.

提交回复
热议问题