Topshelf 使用
Topshelf 簡介
Topshelf是一種創建Windows服務的開源框架
安裝依賴
NuGet搜索Topshelf并安裝

編寫服務類
需要繼承 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

浙公網安備 33010602011771號