安装Topshelf应用程序作为Windows服务

使用Visual Studio Express 2012,我使用Topshelf(版本3.1.107.0)创build了一个控制台应用程序。 该应用程序作为控制台应用程序,但我不知道如何将其作为服务安装。 我已经从Visual Studio(Build,Publish)中发布了项目,以pipe理员身份启动了命令提示符,导航到发布应用程序的文件夹,然后从命令提示符运行setup.exe -install。 该应用程序已安装并运行,但是作为控制台应用程序,而不是Windows服务。 我在这里错过了什么?

对于那些对Topshelf可能不熟悉的人来说,它是一个Windows服务框架,用于.Net,并且应该促进我上面描述的场景 – 作为控制台应用程序开发和debugging,部署为Windows服务。 请参阅http://docs.topshelf-project.com/en/latest/index.html上的文档。

运行您的service.exe install来安装该服务。

有关更多信息,请参阅Topshelf命令行参考文档。

  1. 启动Visual Studio并创build一个新的C#控制台应用程序
  2. 右键点击引用,然后去pipe理NuGet-Packages
  3. 通过NuGet下载并安装Topshelf
  4. 将以下代码粘贴到您的应用程序中,并包含所有导入。
  5. 从“debugging”模式切换到“发布”并构build应用程序。
  6. 以pipe理员身份运行cmd.exe
  7. 导航到控制台

     .\myConsoleApplication\bin\Release\ 
  8. 运行命令

     .\myConsoleApplication.exe install 
  9. 运行命令

     .\myConsoleApplication.exe start 

码:

 using System; using System.Threading; using Topshelf; using Topshelf.Runtime; namespace MyConsoleApplication { public class MyService { public MyService(HostSettings settings) { } private SemaphoreSlim _semaphoreToRequestStop; private Thread _thread; public void Start() { _semaphoreToRequestStop = new SemaphoreSlim(0); _thread = new Thread(DoWork); _thread.Start(); } public void Stop() { _semaphoreToRequestStop.Release(); _thread.Join(); } private void DoWork() { while (true) { Console.WriteLine("doing work.."); if (_semaphoreToRequestStop.Wait(500)) { Console.WriteLine("Stopped"); break; } } } } public class Program { public static void Main() { HostFactory.Run(x => { x.StartAutomatically(); // Start the service automatically x.EnableServiceRecovery(rc => { rc.RestartService(1); // restart the service after 1 minute }); x.Service<MyService>(s => { s.ConstructUsing(hostSettings => new MyService(hostSettings)); s.WhenStarted(tc => tc.Start()); s.WhenStopped(tc => tc.Stop()); }); x.RunAsLocalSystem(); x.SetDescription("MyDescription"); x.SetDisplayName("MyDisplayName"); x.SetServiceName("MyServiceName"); }); } } } 

浏览到该文件夹​​并运行命令:

 AppName.exe install 

您必须以pipe理员身份运行您的命令提示符。

所以这是一个老问题,但我想添加一些命令行选项。

MyTopShelfImplementation.exe install -servicename“MyServiceName”-displayname“我的显示名称”–autostart启动

– 自动启动

是当Windows重新启动。

开始

是在安装之后立即启动服务

现在,您也可以在代码中指定“名称”

  HostFactory.Run(x => { ////x.SetDescription("My Description"); x.SetDisplayName("My Display Name"); x.SetServiceName("My Service Name"); ////x.SetInstanceName("My Instance"); 

因此,如果.exe作为控制台应用程序(或Windows服务)运行,可能是在代码中设置这些值和/或通过命令行传递它们的一些组合。

我期望如果你没有在代码中设置“名称”,你没有通过命令行parameter passing“名称”,那么你会得到控制台的行为。