如何在Windows服务中手动添加安装程序?

时间:2014-05-26 12:21:42

标签: c# windows-services

我编写了一个从ServiceBase继承的抽象类“PollingServiceBase”,以便编写具有覆盖方法的Windows服务。该方法在构造函数中声明的计时器上执行。所以我正在尝试测试它,我写了一个快速的小类,每分钟写一行包括日期时间到文本文件。我需要安装此服务,但是当我无法使用设计器“Add Installer”时,因为PollingServiceBase是抽象的。那么任何人都可以给我一个解决方法或指向一个资源,告诉我如何手动执行此操作?

1 个答案:

答案 0 :(得分:1)

只需在代码中添加新服务:

ServiceInstaller installer = new ServiceInstaller();

并确保正确使用这些属性。

为了更简单,我建议您查看TopShelf。它是一个很好的库,可以编写Windows服务并使其可以通过F5运行。基本上,它是一个控制台应用程序。

这里有关于TopShelf的一些信息:

http://topshelf-project.com/

如果您仍想坚持基本实现,请参阅以下代码:

using (TransactedInstaller installer = new TransactedInstaller())
{
    string path = string.Format("/assemblypath={0}",
                  System.Reflection.Assembly.GetExecutingAssembly().Location);
    string[] arguments = { path };
    InstallContext context = new InstallContext("", arguments);

    using (ProjectInstaller projectInstaller = new ProjectInstaller())
    {
        installer.Installers.Add(projectInstaller);
    }

    installer.Context = context;
    installer.Install(new Hashtable());
}