Topshelf 打包部署Windows服務
阿新 • • 發佈:2018-11-29
1 建立專案(例:控制檯程式)
Nuget 引入Topshelf
類庫
using System;
using System.Threading;
using System.Threading.Tasks;
using Topshelf;
namespace LoginTypeInherit
{
public class Program
{
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod ().ReflectedType);
static void Main(string[] args)
{
// 日誌註冊
log4net.Config.XmlConfigurator.Configure();
try
{
var rc = HostFactory.Run(x =>
{
x.Service<Program>(s =>
{
s.ConstructUsing(name => new Program());
s.WhenStarted(p => p.Start());
s.WhenStopped(p => p.Stop());
});
x.RunAsLocalSystem();
x.SetServiceName("MyServices" );
x.SetDisplayName("我的服務描述");
});
var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());
Environment.ExitCode = exitCode;
}
catch (Exception ex)
{
log.Error("服務啟動出錯", ex);
}
}
/// <summary>
/// 服務啟動
/// </summary>
void Start()
{
log.Info("服務正在啟動");
Task.Run(() =>
{
// 我的服務方法....
});
log.Info("服務已經啟動");
}
/// <summary>
/// 服務停止
/// </summary>
void Stop()
{
log.Info("服務已經停止");
}
}
}
2 打包部署
進入 Debug 資料夾,找到程式的.exe檔案,管理員身份啟動命令視窗,執行MyServices.exe install
命令,即可釋出該服務到本地,效果如下圖,以Windows服務的形式。
啟動服務命令:sc start MyServices.exe
解除安裝服務命令sc delete MyServices
PS: log4net配置
<configuration>
<configSections>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<log4net>
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="Logs/UpdateLoginType.log" />
<rollingStyle value="Date" />
<datePattern value="yyyyMMdd" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
</layout>
</appender>
<root>
<level value="DEBUG" />
<appender-ref ref="RollingLogFileAppender" />
</root>
</log4net>
</configuration>