安装Windows服务 Windows服务不同于普通Windows应用程序。不可能简简单单地通过运行一个EXE就启动Windows服务了。安装一个Windows服务应该通过使用.NET Framework提供的InstallUtil.exe来完成,或者通过诸如一个Microsoft Installer (MSI)这样的文件部署项目完成。 添加服务安装程序
创建一个Windows服务,仅用InstallUtil程序去安装这个服务是不够的。你必须还要把一个服务安装程序添加到你的Windows服务当中,这样便于InstallUtil或是任何别的安装程序知道应用你服务的是怎样的配置设置。 1. 将这个服务程序切换到设计视图 2. 右击设计视图选择“添加安装程序” 3. 切换到刚被添加的ProjectInstaller的设计视图 4. 设置serviceInstaller1组件的属性: 1) ServiceName = My Sample Service 2) StartType = Automatic 5. 设置serviceProcessInstaller1组件的属性 1) Account = LocalSystem 6. 生成解决方案
在完成上面的几个步骤之后,会自动由Visual Studio产生下面的源代码,它包含于ProjectInstaller.cs这个源文件内。 using System; using System.Collections; using System.ComponentModel; using System.Configuration.Install;
namespace CodeGuru.MyWindowsService { /// <summary> /// Summary description for ProjectInstaller. /// </summary> [RunInstaller(true)] public class ProjectInstaller : System.Configuration.Install.Installer { private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller1; private System.ServiceProcess.ServiceInstaller serviceInstaller1; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null;
public ProjectInstaller() { // This call is required by the Designer. InitializeComponent();
// TODO: Add any initialization after the InitComponent call }
#region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.serviceProcessInstaller1 = new System.ServiceProcess.ServiceProcessInstaller(); this.serviceInstaller1 = new System.ServiceProcess.ServiceInstaller(); // // serviceProcessInstaller1 // this.serviceProcessInstaller1.Account = System.ServiceProcess.ServiceAccount.LocalSystem; this.serviceProcessInstaller1.Password = null; this.serviceProcessInstaller1.Username = null; // // serviceInstaller1 // this.serviceInstaller1.ServiceName = "My Sample Service"; this.serviceInstaller1.StartType = System.ServiceProcess.ServiceStartMode.Automatic; // // ProjectInstaller // this.Installers.AddRange(new System.Configuration.Install.Installer[] {this.serviceProcessInstaller1, this.serviceInstaller1}); } #endregion } }
|