如何开发并一键发布WindowsService项目(netcore普通项目)

netcore下开发windows服务如果是web项目的话,由于aspnetcore本身是支持的,把默认的host.Run改为host.RunAsService就可以了。

但是普通的netcore的控制台项目我终于找到了如下方式来实现:

1. 打开vs 选择创建一个新的netcore 控制台项目

Nuget添加如下引用

  1. Microsoft.Extensions.Hosting
  2. System.ServiceProcess.ServiceController

新建一个ServiceBaseLifetime.cs 并将下面的内容复制进去

public class ServiceBaseLifetime : ServiceBase, IHostLifetime
{
private readonly TaskCompletionSource _delayStart = new TaskCompletionSource(); public ServiceBaseLifetime(IApplicationLifetime applicationLifetime)
{
ApplicationLifetime = applicationLifetime ?? throw new ArgumentNullException(nameof(applicationLifetime));
} private IApplicationLifetime ApplicationLifetime { get; } public Task WaitForStartAsync(CancellationToken cancellationToken)
{
cancellationToken.Register(() => _delayStart.TrySetCanceled());
ApplicationLifetime.ApplicationStopping.Register(Stop); new Thread(Run).Start(); // Otherwise this would block and prevent IHost.StartAsync from finishing.
return _delayStart.Task;
} private void Run()
{
try
{
Run(this); // This blocks until the service is stopped.
_delayStart.TrySetException(new InvalidOperationException("Stopped without starting"));
}
catch (Exception ex)
{
_delayStart.TrySetException(ex);
}
} public Task StopAsync(CancellationToken cancellationToken)
{
Stop();
return Task.CompletedTask;
} // Called by base.Run when the service is ready to start.
protected override void OnStart(string[] args)
{
_delayStart.TrySetResult(null);
base.OnStart(args);
} // Called by base.Stop. This may be called multiple times by service Stop, ApplicationStopping, and StopAsync.
// That's OK because StopApplication uses a CancellationTokenSource and prevents any recursion.
protected override void OnStop()
{
ApplicationLifetime.StopApplication();
base.OnStop();
}
}

新建一个ServiceBaseLifetimeHostExtensions.cs 并将下面的内容复制进去

public static class ServiceBaseLifetimeHostExtensions
{
public static IHostBuilder UseServiceBaseLifetime(this IHostBuilder hostBuilder)
{
return hostBuilder.ConfigureServices((hostContext, services) => services.AddSingleton<IHostLifetime, ServiceBaseLifetime>());
} public static void RunAsService(this IHostBuilder hostBuilder)
{
hostBuilder.UseServiceBaseLifetime().Build().Run();
} public static Task RunAsServiceAsync(this IHostBuilder hostBuilder)
{
return hostBuilder.UseServiceBaseLifetime().Build().RunAsync(CancellationToken.None);
}
}

新建一个服务类 TestService.cs 并写入以下内容(该服务就是每1秒往d:\log.txt写入当前时间)

public class TestService: IHostedService,IDisposable
{
readonly System.Timers.Timer tmBak = new System.Timers.Timer(); public TestService()
{
tmBak.Interval = ;//1秒执行1次
tmBak.AutoReset = true;//执行1次false,一直执行true
tmBak.Enabled = true;
tmBak.Elapsed += (sender, eventArgs) =>
{
using (StreamWriter sw = new StreamWriter("D:\\log.txt",true))
{
sw.WriteLine($"AntDeploy Windows服务:{DateTime.Now:yyyy-MM-dd HH:mm:ss}");
}
};
} public Task StartAsync(CancellationToken cancellationToken)
{
tmBak.Start();
return Task.CompletedTask;
} public Task StopAsync(CancellationToken cancellationToken)
{
tmBak.Stop();
return Task.CompletedTask;
} public void Dispose()
{
this.tmBak.Dispose();
}
}

编辑 Program.cs 写入如下内容,保证既可以作为控制台打开又可以作为windows服务运行:

class Program
{
// P/Invoke declarations for Windows.
[DllImport("kernel32.dll")] static extern IntPtr GetConsoleWindow();
[DllImport("user32.dll")] static extern bool IsWindowVisible(IntPtr hWnd);
public static bool HaveVisibleConsole()
{
return RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
IsWindowVisible(GetConsoleWindow())
:
Console.WindowHeight > ;
} private static async Task Main(string[] args)
{
var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
var pathToContentRoot = Path.GetDirectoryName(pathToExe);
Directory.SetCurrentDirectory(pathToContentRoot); var isService = !(Debugger.IsAttached || args.Contains("--console")); if (HaveVisibleConsole()) isService = false;
var builder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<TestService>();
}); if (isService)
{
await builder.RunAsServiceAsync();
}
else
{
await builder.RunConsoleAsync();
}
}
}

一键发布到服务器,在工程上点击右键 然后选择 AntDeploy

AntDeploy是我开发的一款开源一键部署vs插件(也是支持脱离vs单独使用的一个开源工具)

开源地址:https://github.com/yuzd/AntDeployAgent

配置AntDeploy

添加一个环境 名字叫 测试 然后 在 测试环境里面添加 windows服务器 这里我做测试就添加就是我本机,注意Host里面是填写格式为:ip:端口号

注意:Token不是windows服务器的密码!!!是安装agent后,agent的配置文件里面配置的Token(你自己自定义配置的)
注意:Port不是你要发布的项目的端口号!!!是安装agent后,agent的配置文件里面配置的端口号(你自己自定义配置的)
点击【Connect Test】按钮进行确认agent可以成功链接,否则会发布失败
如果【Connect Fail】失败 请查看 #10

进入 WindowsService Tab界面

Sdk类型选择 netcore
ServiceName 填写上面我们设置的名称:[TestService]

点击 【Deploy】按钮进行发布

确认服务器无误 点击 【是】开始执行一键部署
如果发布出现错误会出现下图所示:

可以在Log里面查看失败原因是因为我部署agent没有用管路员权限 报权限不足失败 需要用管理员权限运行agent才行

部署成功 如下图:

查看D盘下是否log.txt是否正常每隔1秒写入了当前时间

这里演示的是windows服务上没有这个service
所以自动创建了。
如果service已存在的情况 Deploy 就会全量覆盖 不会重新创建site的。
如果想要覆盖时排除指定文件 可以在 Setting Tab界面的IgnoreList里面增加(支持正则)

netcore开发windows普通服务(非Web)并一键发布到服务器的更多相关文章

  1. iNeuOS工业互联平台,.NETCore开发的视频服务组件iNeuVideo,RTSP转WebSocket

    目       录 1.      概述... 2 2.      将来集成到iNeuOS平台演示... 3 3.      iNeuVideo结构... 3 4.      iNeuVideo部署及 ...

  2. 使用C#编程语言开发Windows Service服务

    转载-https://www.cnblogs.com/yubao/p/8443455.html Create Windows Service project using Visual Studio C ...

  3. C#开发Windows Services服务--服务安装失败的解决办法

    问题1:“System.Security.SecurityException:未找到源,但未能搜索某些或全部事件日志.不可访问的日志: Security.” 正在运行事务处理安装. 正在开始安装的“安 ...

  4. 手动打包MVC项目成Web Deploy包,发布至服务器

    ①确保服务器上安装了Web Deploy,可以使用微软Web Paltform Installer安装.https://www.microsoft.com/web/downloads/platform ...

  5. windows部署服务(WDS)

     1.服务器端os:windows server2003R2,windows server 2008,windows server 2008 R2 文件系统:NTFS 必须需要AD架构 网络中需要微软 ...

  6. C# DateTime的11种构造函数 [Abp 源码分析]十五、自动审计记录 .Net 登陆的时候添加验证码 使用Topshelf开发Windows服务、记录日志 日常杂记——C#验证码 c#_生成图片式验证码 C# 利用SharpZipLib生成压缩包 Sql2012如何将远程服务器数据库及表、表结构、表数据导入本地数据库

    C# DateTime的11种构造函数   别的也不多说没直接贴代码 using System; using System.Collections.Generic; using System.Glob ...

  7. 使用Visual Studio 2015 Community 开发windows服务

    昨天研究在.NET下开发Windows服务程序,期间遇到一些小问题,这里仅将自己的开发过程和需要注意的地方写下和广大网友分享……  1.基础   Windows服务是指系统启动时能够自己运行的程序.W ...

  8. C#开发Windows服务 附简单实例实现禁止QQ运行

    本实例主要实现下面三个基本功能 1.C#开发windows服务 2.禁止QQ等程序运行 3.为windows服务创建自动安装程序 下面针对这三个基本功能进行实现 一.C#开发windows服务 Win ...

  9. VS2013开发Windows服务项目

    这篇随笔里,我将介绍如何用VS2013开发Windows服务项目,实现的功能是定时发送电子邮件. 开发环境:VS2013,SQL Server2008,采用C#语言开发 步骤一:创建Windows服务 ...

随机推荐

  1. JVM 学习(一)反射、垃圾回收、异常处理--- 2019年4月

    1.JVM 基础知识点 JVM 虚拟机包含了:自动内存管理器.垃圾回收(垃圾回收调优). 执行顺序:Java 代码 --- .class 字节码文件(加载到虚拟机中) --- Java 类放在方法区中 ...

  2. Intellij IDEA 阅读源码的 4 个绝技,我必须分享给你!

    前段时间分享了<阅读跟踪 Java 源码的几个小技巧>是基于 Eclipse 版本的,看大家的留言都是想要 IDEA 版本的源码阅读技巧. 所以,为了满足众多 IDEA 粉丝的要求,栈长我 ...

  3. springcloud之config配置中心-Finchley.SR2版

    本篇和大家分享的是springcloud-config配置中心搭建,写到这里突然想起自己曾今开源过基于Redis发布订阅编写的一个配置中心,刚看了git星数有点少哈哈,这里顺势发个连接欢迎大侠们点赞: ...

  4. [Abp vNext 源码分析] - 1. 框架启动流程分析

    一.简要说明 本篇文章主要剖析与讲解 Abp vNext 在 Web API 项目下的启动流程,让大家了解整个 Abp vNext 框架是如何运作的.总的来说 ,Abp vNext 比起 ABP 框架 ...

  5. 死磕 java集合之ConcurrentHashMap源码分析(一)

    开篇问题 (1)ConcurrentHashMap与HashMap的数据结构是否一样? (2)HashMap在多线程环境下何时会出现并发安全问题? (3)ConcurrentHashMap是怎么解决并 ...

  6. 【反编译系列】三、反编译神器(jadx)

    版权声明:本文为HaiyuKing原创文章,转载请注明出处! 概述 今天在看玩Android网站,搜索反编译的时候,才发现有个更好用的反编译工具.特此记录下. 下载 http://www.wanand ...

  7. 小议 localStorage

    前言 什么是 localStorage? 在HTML5中,新加入了一个localStorage特性,这个特性主要是用来作为本地存储来使用的,解决了cookie存储空间不足的问题(cookie中每条co ...

  8. k8s部署使用Dashboard(十)--技术流ken

    安装Dashboard 前面博客Kubernetes 所有的操作我们都是通过命令行工具 kubectl 完成的.为了提供更丰富的用户体验,Kubernetes 还开发了一个基于 Web 的 Dashb ...

  9. PHP类和函数注释大全

    每次要用PHP的某个功能的时候,都要去查一下,于是决定将PHP所有类和函数都整理出来,加上注释 大致实现 将php.jar文件解压,取出目录stubs 将stubs中的所有php文件中的注释去掉,并做 ...

  10. Asp.Net Core在CentOS部署与注意

    部署具体步骤参考:将ASP.NET Core应用程序部署至生产环境中(CentOS7) 1.wwwroot是放静态文件的,Startup的配置里面要app.UseStaticFiles(); 2.在不 ...