我们知道.net core支持console和web开发,分别叫做.net core程序和asp.net core.
查询.net core官方文档,并没有介绍编写windows service相关的说明,一直以来以为dotnet core不支持windows service开发,知道查看asp.net core部署文档中提到可以部署在Windows service中,从而确定dotnet是可以开发Windows service的.
查看asp.net core的Windows宿主的源代码Microsoft.AspNetCore.Hosting.WindowsServices,发现最终给宿主是继承自System.ServiceProcess.ServiceBase,同时实现了OnStart以及OnStop等一些列方法.我们知道dotnet framework 中的service基类也是System.ServiceProcess.ServiceBase,所以可以试下按照传统的dotnet framework的方法尝试开发Windowsservice.
我们新建一个dotnet console程序,添加一个windows服务,取名WinService
默认代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
namespace WindowsService.Demo
{
partial class WinService: ServiceBase
{
public WinService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
// TODO: 在此处添加代码以启动服务。
}
protected override void OnStop()
{
// TODO: 在此处添加代码以执行停止服务所需的关闭操作。
}
}
}
我们发现默认是会报dll缺失的错误,我们添加nuget引用System.ServiceProcess.ServiceController.
修改main方法,运行WinService即可.dotnet没有提供界面画的安装程序,可以通过sc命令安装服务.
sc create myservicename binpath="***.exe"
using System;
using System.ServiceProcess;
namespace WindowsService.Demo
{
class Program
{
static void Main(string[] args)
{
ServiceBase[] services = new ServiceBase[] { new WinService() };
ServiceBase.Run(services);
}
}
}
发布时选择独立部署类型,即可生产可独立运行大的exe程序