没有Visual Studio干扰的Windows服务

Eam*_*nne 11 .net windows-services designer

我想在没有Visual Studio设计者"帮助"的情况下创建和管理Windows服务应用程序.

由于这是.NET,并且由MSDN和设计人员做什么来判断,这意味着继承Installer,构建和处理ServiceProcessInstaller以及ServiceInstaller能够管理服务器的安装时执行.

运行时,这意味着创建一个ServiceBase子类并从Main使用ServiceBase.Run(并覆盖各种ServiceBase事件处理方法)开始.

但是,当我这样做时,Visual studio坚持将InstallerServiceBase子类视为设计者编辑的文件.这并不完全有助于提高可读性,更不用说它通常根本无法处理手写代码. 我想避免设计师让事情变得易于管理(以避免模糊不清谁知道什么时候运行,特别是对于那些测试和调试很棘手的代码,例如必须安装才能运行的Windows服务),并且还能够在运行时指定服务名称,而不是在编译时指定服务名称 - 设计者不支持.

如何在没有所有垃圾的情况下创建Windows服务应用程序?

Kev*_*uth 10

ServiceBase源于Component.要禁用设计器视图,您可以附加属性,如下所示:

[System.ComponentModel.DesignerCategory("Code")]
public class MyService : ServiceBase
{

}
Run Code Online (Sandbox Code Playgroud)


adr*_*anm 6

因为我经常创建服务,所以这样做:

我有一个看起来像这样的公共基类:

internal class ServiceRunner : ServiceBase {
   protected static void Startup(string[] args, ServiceRunner instance, bool interactiveWait) {    
    if (instance == null)
        throw new ArgumentNullException("instance");

    if (Environment.UserInteractive) {
        instance.OnStart(args);
        if (interactiveWait) {
            Console.WriteLine("Press any key to stop service");
            Console.ReadKey();
        }
        instance.OnStop();
    }
    else
        Run(instance);
}
Run Code Online (Sandbox Code Playgroud)

然后我创建这样的所有服务

internal class MyService : ServiceRunner
{
    public MyService() {
        ServiceName = ConfigurationManager.AppSettings["MyServiceName"];
    }

    private static void Main(string[] args) {
        Startup(args, new MyService(), true);
    }

    protected override void OnStart(string[] args) {
        base.OnStart(args);
        ...
    }

    protected override void OnStop() {
        ...
        base.OnStop();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我可以通过在调试器或命令行中运行它来测试服务.

安装时我使用命令行

sc create ServiceName binPath= C:\...\MyService.exe
Run Code Online (Sandbox Code Playgroud)

(我无法阻止设计师双击打开)


Chr*_*aas -1

VS 确实添加了一些额外的东西,但我不会真正担心它。这是在 VS2005 中手动创建简单服务的教程,它也应该适用于新版本。

http://www.codeproject.com/KB/system/WindowsService.aspx