ASP.NET Core框架学习之Topshelf创建Windows服务

Topshelf是一个开源的跨平台的宿主服务框架,只需要几行代码就可以构建一个很方便使用的windows服务。

首先安装nuget包 Topshelf。

创建一个.net core控制台程序

 1  static void Main(string[] args)
 2  {
 3             #region 容器注入
 4             var services = new ServiceCollection();14             services.AddScoped(typeof(ServiceRunner));
15             var serviceProvider = services.BuildServiceProvider(); 
16             #endregion

28             #region topshelf
29             HostFactory.Run(x =>
30             {
31                 x.Service<ServiceRunner>(s =>                      
32                 {
33                     s.ConstructUsing(name => serviceProvider.GetService<ServiceRunner>());
34                     s.WhenStarted(tc => tc.Start());
35                     s.WhenStopped(tc => tc.Stop());
36                 }
37                     );
38                 x.RunAsLocalSystem();
39                 x.EnablePauseAndContinue();
40                 x.SetDescription("QuartzWechatMsg_");        //安装服务后,服务的描述
41                 x.SetDisplayName("QuartzWechatMsg");                       //显示名称
42                 x.SetServiceName("QuartzWechatMsg");                       //服务名称
43             });
44             #endregion
45             Console.ReadLine();
46  }

 

 1  public class ServiceRunner 
 2 {
 3         public ServiceRunner()
 4         {
 5         }
 6 
 7         public void Start()
 8         {
 9             Log4Util.Info("消息发送服务已启动");
10             //要执行的任务逻辑
11         }
12 
13         public void Stop()
14         {
15             Log4Util.Info("消息发送服务已关闭");
16         }
17 }        

  这样一个简单的Windows服务就开发完了,接下来只需要一些简单的配置即可。

  安装:*.exe install
  启动:*.exe start
  卸载:*.exe uninstall
 
  值得一提的是,.net core 默认情况下,是不会生成 .exe程序的,需要在项目上右键编辑xxx.csproj,添加一行
 <RuntimeIdentifier>win10-x64</RuntimeIdentifier>
<PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <RuntimeIdentifier>win10-x64</RuntimeIdentifier>
  </PropertyGroup>

重新生成解决方案,即可在根目录下发现一个 win10-x64文件夹,exe就生成在该文件夹内。

 

posted @ 2019-06-28 10:20  唐磊(Jason)  阅读(293)  评论(0编辑  收藏  举报