在 .net 核心中编写 windows 服务

Writing windows service in .net core

我的问题是如何在 .net 核心中编写我们在以前的 .net 版本中编写的 windows 服务?

很多 links/articles 解释了如何将 .net 核心应用程序托管为 windows 服务。所以这是我创建 windows 服务的唯一方法?

如果是,谁能提供 links/example

谢谢!

不确定是否有执行此操作的默认方法。但是,您可以让您的核心应用程序继承自 ServiceBase 并实施必要的覆盖。我们在我们的应用程序中这样做(请注意,我们针对的是完整框架,而不是核心)。最初的想法来自以下文章:

请注意,这些文章仍然引用 DNX(从 .NET Core 测试版开始)- 现在您的核心应用程序将编译为 exe,因此您可以调整它们的示例以适应这一点。

This is 使用 .net 核心构建 windows 服务的一种方法。

It is built using P/Invoke calls into native windows assemblies.

编写 windows 服务的示例(取自 github 项目页面):

using DasMulli.Win32.ServiceUtils;

class Program
{
    public static void Main(string[] args)
    {
        var myService = new MyService();
        var serviceHost = new Win32ServiceHost(myService);
        serviceHost.Run();
    }
}

class MyService : IWin32Service
{
    public string ServiceName => "Test Service";

    public void Start(string[] startupArguments, ServiceStoppedCallback serviceStoppedCallback)
    {
        // Start coolness and return
    }

    public void Stop()
    {
        // shut it down again
    }
}

它是 not perfect 但恕我直言,它非常好。

这是在 .net Core(控制台应用程序)中构建 windows 服务的另一种简单方法

DotNetCore.WindowsService

允许将 .net 核心应用程序作为 windows 服务托管的简单库。

安装

使用 nuget: 安装包PeterKottas.DotNetCore.WindowsService

用法

  1. 创建 .NETCore 控制台应用程序。
  2. 创建您的第一个服务,如下所示:

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

    ServiceRunner<ExampleService>.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. 运行 没有参数的服务,它像控制台应用程序一样运行。

  5. 运行 使用 action:install 的服务,它将安装该服务。
  6. 运行 使用 action:uninstall 的服务,它将卸载该服务。
  7. 运行 使用 action:start 的服务,它将启动服务。
  8. 运行 带有 action:stop 的服务,它将停止服务。