Topshelf 使用

Topshelf 简介

Topshelf是一种创建Windows服务的开源框架

安装依赖

NuGet搜索Topshelf并安装
image

编写服务类

需要继承 Topshelf.ServiceControl 类,并实现 bool Start(Topshelf.HostControl hostControl) 和 bool Stop(Topshelf.HostControl hostControl) 方法

using NLog;
using SqlSugar;
using SunCreate.Yqaf.Contract;
using SunCreate.Yqaf.Server.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using WCFCommon;
using WCFServiceProxy;

namespace SunCreate.Yqaf.Server.ServiceHost
{
    /// <summary>
    /// Windows服务
    /// </summary>
    public class WindowsService : Topshelf.ServiceControl
    {
        private Logger _log = NLog.LogManager.GetCurrentClassLogger();

        public bool Start(Topshelf.HostControl hostControl)
        {
            int serverPort = int.Parse(System.Configuration.ConfigurationManager.AppSettings["ServerPort"]);
            Assembly serviceAssembly = Assembly.GetAssembly(typeof(BaseDataService));
            Assembly contractAssembly = Assembly.GetAssembly(typeof(IBaseDataService));
            string contractNamespace = "SunCreate.Yqaf.Contract";

            SqlSugarUtil.Init();

            HostFactory.CreateHosts(serverPort, serviceAssembly, contractAssembly, contractNamespace);

            ServiceFactory.StartAllService();

            //CreateModels(); //生成SqlSugar实体类

            _log.Info("WindowsService启动");
            return true;
        }

        public bool Stop(Topshelf.HostControl hostControl)
        {
            ServiceFactory.StopAllService().Wait();
            _log.Info("WindowsService停止");
            return true;
        }

        private void CreateModels()
        {
            try
            {
                SqlSugarClient db;
                db = SqlSugarUtil.CreateSqlSugarClient();
                SqlSugarUtil.CreateModels(db);
                Console.WriteLine("生成SqlSugar实体类成功");
            }
            catch (Exception ex)
            {
                Console.WriteLine("生成SqlSugar实体类出错:" + ex.Message);
            }
        }
    }
}

程序入口

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Topshelf;

namespace SunCreate.Yqaf.Server.ServiceHost
{
    class Program
    {
        static void Main(string[] args)
        {
            HostFactory.Run(x =>
            {
                x.Service<WindowsService>();
                x.RunAsLocalSystem();

                x.SetDescription("XXX服务");
                x.SetDisplayName("XXX服务");
                x.SetServiceName("MyService");
            });

            Console.Read();
        }
    }
}

部署服务

在当前文件夹下打开 CMD 执行命令
安装:MyService.exe install
启动:MyService.exe start
卸载:MyService.exe uninstall

posted @ 2025-07-01 12:33  0611163  阅读(26)  评论(0)    收藏  举报