1)TopShelf安装:
使用平台: .NET 3.5 Service Pack 1或 .NET 4.0的Windows操作系统
引用Topshelf.dll的途径:
方法一:在解决方案或者项目中,使用NuGet(工具->库程序包管理器->程序包管理器控制台),输入以下命令:
nuget Install-Package Topshelf
方法二:点击这里下载(http://github.com/topshelf/Topshelf/downloads)
2)简单实例:
a. 新建项目,选择控制台应用程序,引用TopShelf.dll
b. 添加SampleService.cs
public class SampleService{static readonly LogWriter _log = HostLogger.Get<SampleService>();public void Start(){_log.Info("SampleService Start...");}public void Stop(){_log.Info("SampleService Stop...");}}
这里采用TopShelf本身的日志功能即 LogWriter _log =HostLogger.Get<SampleService>();TopShelf本身提供的日志功能可以在控制台中输出日志信息。如果要更强大的日志功能可以结合Log4net或者NLog来实现日志记录。
c. 在Program.cs中添加如下代码
class Program{static void Main(string[] args){HostFactory.Run(x =>{x.UseAssemblyInfoForServiceInfo();x.Service<SampleService>(s =>{s.ConstructUsing(name => new SampleService());s.WhenStarted(tc => tc.Start());s.WhenStopped(tc => tc.Stop());});x.SetServiceName("ServiceName");x.SetDisplayName("DisplayName");x.SetInstanceName("InstanceName");x.SetDescription("Sample Service's Description");x.RunAsLocalSystem();x.StartAutomatically();});}}
d. 在VS中直接运行实例,即可调试服务程序
e. 安装服务,运行->进入应用程序的目录,输入xxx.exe install命令,即可安装成功(安装失败的话,尝试以管理员身份运行命令提示符程序)
f. 在服务管理器中查看(比对Programs.cs中的设置)
g. 卸载服务,与安装类似,输入在命令提示符工具中输入 xxx.exe uninstall
736

被折叠的 条评论
为什么被折叠?



