使用Topshelf 5步建立Windows 服務

使用Topshelf建立Windows 服務簡要的介紹了建立Windows服務的另外一種方法,老外的一篇文章Create a .NET Windows Service in 5 steps with Topshelf經過5個步驟詳細的介紹使用使用Topshelf建立Windows 服務。Topshelf是一個開源的跨平臺的宿主服務框架,支持Windows和Mono,只須要幾行代碼就能夠構建一個很方便使用的服務宿主。html

一、Topshelf的代碼託管在http://topshelf-project.com/,能夠在這裏下載到最新的代碼。windows

二、使用Visual Studio建立一個控制檯應用程序引用程序集TopShelf.dll 合log4net.dll 。app

三、建立一個簡單的服務類,裏面包含兩個方法Start和Stop,這個服務只是演示代碼,因此咱們每隔5秒輸出一個日誌。框架

using System;
using System.Timers;
using log4net;

namespace SampleWindowsService
{
public class SampleService
{
private Timer _timer = null;
readonly ILog _log = LogManager.GetLogger(typeof(SampleService));

public SampleService()
{
double interval = 5000;
_timer = new Timer(interval);
_timer.Elapsed += new ElapsedEventHandler(OnTick);
}

protected virtual void OnTick(object sender, ElapsedEventArgs e)
{
_log.Debug("Tick:" + DateTime.Now.ToLongTimeString());
}

public void Start()
{
_log.Info("SampleService is Started");

_timer.AutoReset = true;
_timer.Enabled = true;
_timer.Start();
}

public void Stop()
{
_log.Info("SampleService is Stopped");

_timer.AutoReset = false;
_timer.Enabled = false;
}
}
}
四、在Main方法中使用Topshelf宿主咱們的服務,主要是告訴Topshelf如何設置咱們的服務的配置和啓動和中止的時候的方法調用。
using System.IO;
using log4net.Config;
using Topshelf;

namespace SampleWindowsService
{
class Program
{
static void Main(string[] args)
{
XmlConfigurator.ConfigureAndWatch(
new FileInfo(".\\log4net.config"));

var host = HostFactory.New(x =>
{
x.EnableDashboard();
x.Service<SampleService>(s =>
{
s.SetServiceName("SampleService");
s.ConstructUsing(name => new SampleService());
s.WhenStarted(tc =>
{
XmlConfigurator.ConfigureAndWatch(
new FileInfo(".\\log4net.config"));
tc.Start();
});
s.WhenStopped(tc => tc.Stop());
});

x.RunAsLocalSystem();
x.SetDescription("SampleService Description");
x.SetDisplayName("SampleService");
x.SetServiceName("SampleService");
});

host.Run();
}
}
}
四、配置Log4net和運行咱們的服務,服務能夠看成控制檯來運行,這在開發的時候是很是方便的。服務的安裝很方便
SampleWindowsService.exe install
安裝成功後,能夠經過服務控制檯啓動,或者也能夠經過一下命令運行
SampleWindowsService.exe start
服務的卸載方法也很是簡單了
SampleWindowsService.exe uninstall
相關文章
相關標籤/搜索