Topshelf 是一個用來部署 基于.NET Framework 開發(fā)的服務(wù) 的框架。它極大的簡化服務(wù)創(chuàng)建與部署過程,它支持將控制臺應(yīng)用程序部署為服務(wù)。開發(fā)過 Windows 服務(wù)程序的同學(xué)應(yīng)該都比較清楚,代碼調(diào)試和服務(wù)部署上相對來說都過于麻煩,當(dāng)我第一次接觸 Topshelf 的時候,發(fā)現(xiàn)它是如此簡單,瞬間對之前寫的 Windows 服務(wù)程序表示深深的嘆息 ......

for what?
Topshelf 安裝
通過 NuGet 安裝 Topshelf 包。
Install-Package Topshelf
Topshelf 配置
以下是我們以 Topshelf 來部署的一個 gRPC 服務(wù)代碼,Topshelf 關(guān)鍵配置在 Main 方法內(nèi),更多的配置建議閱讀一下 官方文檔,沒什么特別復(fù)雜的地方,相信大家肯定能看懂。
class Program
{
static void Main(string[] args)
{
// 配置和運行宿主服務(wù)
HostFactory.Run(x =>
{
// 指定服務(wù)類型。這里設(shè)置為 CacheService
x.Service<CacheService>(s =>
{
// 通過 new CacheService() 構(gòu)建一個服務(wù)實例
s.ConstructUsing(name => new CacheService());
// 當(dāng)服務(wù)啟動后執(zhí)行什么
s.WhenStarted(tc => tc.Start());
// 當(dāng)服務(wù)停止后執(zhí)行什么
s.WhenStopped(tc => tc.Stop());
});
// 服務(wù)用本地系統(tǒng)賬號來運行
x.RunAsLocalSystem();
// 服務(wù)描述信息
x.SetDescription("緩存服務(wù)");
// 服務(wù)顯示名稱
x.SetDisplayName("CacheService");
// 服務(wù)名稱
x.SetServiceName("CacheService");
});
}
}
public class CacheService
{
private readonly string host = ConfigurationManager.AppSettings["Host"];
private readonly string port = ConfigurationManager.AppSettings["Port"];
readonly Server server;
public CacheService()
{
server = new Server
{
Services = { MDCache.BindService(new CacheServiceImpl()) },
Ports = { new ServerPort(host, Convert.ToInt32(port), ServerCredentials.Insecure) }
};
}
public void Start() { server.Start(); }
public void Stop() { server.ShutdownAsync(); }
}
安裝服務(wù)
通過以上配置,確保程序集 Build 成功后,進入 bin\Debug 目錄下,執(zhí)行 install 命令,一個 Windows 服務(wù)就誕生了。(如果出現(xiàn)需要以管理員身份啟動的提示,重新以管理員身份啟動 cmd )。
xxx.exe install

服務(wù)安裝
啟動服務(wù)
安裝成功后我們可以在 Windows 服務(wù)下找到并啟動它。

服務(wù)信息
注意:因為 serviceName 必須是唯一的,如果我們希望在同一臺機器上運行多個相同的服務(wù),那么我們需要注釋掉硬編碼設(shè)置的 ServiceName 和 DisplayName ,然后通過命令參數(shù)來動態(tài)指定服務(wù)名稱。
// 服務(wù)顯示名稱
//x.SetDisplayName("CacheService");
// 服務(wù)名稱
//x.SetServiceName("CacheService");
xxx.exe install -servicename cacheService
xxx.exe install -servicename cacheService1

多個相同服務(wù)
服務(wù)卸載
卸載和啟動的命令保持一致,只需要把 install 改成 uninstall 。

卸載

指定服務(wù)名稱卸載