安装一个可执行文件,该文件包含扩展 ServiceBase的类。该类由安装实用工具(如 InstallUtil.exe)在安装服务应用程序时调用。
命名空间:System.ServiceProcess
程序集:System.ServiceProcess(在 system.serviceprocess.dll 中)
ServiceProcessInstaller 执行可执行文件中的所有服务的公共操作。安装实用工具使用它来写与要安装服务关联的注册表值。
若要安装服务,请创建一个从 Installer 继承的项目安装程序类,然后将该类上的 RunInstallerAttribute 设置为 true。在项目中,为每个服务应用程序实例化一个 ServiceProcessInstaller 实例,并为应用程序中的每个服务实例化一个 ServiceInstaller 实例。最后,向项目安装程序类添加 ServiceProcessInstaller 实例和 ServiceInstaller 实例。
当 InstallUtil.exe 运行时,该实用工具在服务程序集内查找 RunInstallerAttribute 设置为 true 的类。通过将类添加到与项目安装程序关联的 Installers 集合来向服务程序集添加类。如果 RunInstallerAttribute 为 false,安装实用工具将忽略项目安装程序。
对于 ServiceProcessInstaller 实例,可修改的属性包括指定服务应用程序在登录用户之外的帐户下运行。可指定运行该服务所使用的特定 Username 和 Password 对,或者可使用 Account 指定该服务是在计算机的系统帐户、本地或网络服务帐户还是用户帐户下运行。
注意 |
---|
计算机的“系统”帐户与“管理员”帐户不同。 |
通常,不在自己的代码中调用 ServiceInstaller 上的方法,这些方法通常只由安装实用工具来调用。在安装进程中,安装实用工具自动调用 ServiceProcessInstaller.Install 和 ServiceInstaller.Install 方法。必要时,它退出故障,方法是在以前安装的所有组件上调用 Rollback(或 ServiceInstaller.Rollback)。
使用项目安装程序的 Installer.Context,应用程序的安装例程自动维护有关已安装组件的信息。该状态信息作为 ServiceProcessInstaller 实例而持续更新,并且每个 ServiceInstaller 实例均由实用工具来安装。通常,不必通过代码显式修改此状态信息。
实例化 ServiceProcessInstaller 将导致调用基类构造函数 ComponentInstaller。
下面的示例创建一个名为 MyProjectInstaller 的项目安装程序,它从 Installer 继承。假定有一个服务可执行文件,它包含“Hello-World Service 1”和“Hello-World Service 2”两个服务。在 MyProjectInstaller 的构造函数(它由安装实用工具调用)内,为每个服务创建若干 ServiceInstaller 对象,并为可执行文件创建一个 ServiceProcessInstaller。为使安装实用工具将 MyProjectInstaller 识别为有效安装程序,RunInstallerAttribute 属性被设置为 true。
首先在进程安装程序和服务安装程序上设置可选属性,然后向 Installers 集合添加这些安装程序。当安装实用工具访问 MyProjectInstaller 时,将依次安装通过调用 InstallerCollection.Add 添加到 Installers 集合的对象。在该过程中,安装程序维护状态信息,这些信息指示哪些对象已安装,以便在安装失败时可依次退出各个对象。
通常,不显式实例化项目的安装程序类。您可以创建该类并添加 RunInstallerAttribute,但实际上是由安装实用工具来调用该类并初始化它。
using System; using System.Collections; using System.Configuration.Install; using System.ServiceProcess; using System.ComponentModel; [RunInstallerAttribute(true)] public class MyProjectInstaller: Installer{ private ServiceInstaller serviceInstaller1; private ServiceInstaller serviceInstaller2; private ServiceProcessInstaller processInstaller; public MyProjectInstaller(){ // Instantiate installers for process and services. processInstaller = new ServiceProcessInstaller(); serviceInstaller1 = new ServiceInstaller(); serviceInstaller2 = new ServiceInstaller(); // The services run under the system account. processInstaller.Account = ServiceAccount.LocalSystem; // The services are started manually. serviceInstaller1.StartType = ServiceStartMode.Manual; serviceInstaller2.StartType = ServiceStartMode.Manual; // ServiceName must equal those on ServiceBase derived classes. serviceInstaller1.ServiceName = "Hello-World Service 1"; serviceInstaller2.ServiceName = "Hello-World Service 2"; // Add installers to collection. Order is not important. Installers.Add(serviceInstaller1); Installers.Add(serviceInstaller2); Installers.Add(processInstaller); } }