ServiceProcessInstaller ServiceProcessInstaller ServiceProcessInstaller ServiceProcessInstaller Class

Definição

Instala um executável que contém classes que estendem ServiceBase.Installs an executable containing classes that extend ServiceBase. Essa classe é chamada por utilitários de instalação, como InstallUtil.exe, ao instalar um aplicativo de serviço.This class is called by installation utilities, such as InstallUtil.exe, when installing a service application.

public ref class ServiceProcessInstaller : System::Configuration::Install::ComponentInstaller
public class ServiceProcessInstaller : System.Configuration.Install.ComponentInstaller
type ServiceProcessInstaller = class
    inherit ComponentInstaller
Public Class ServiceProcessInstaller
Inherits ComponentInstaller
Herança

Exemplos

O exemplo a seguir cria um instalador de projeto chamado MyProjectInstaller, que herda de Installer.The following example creates a project installer called MyProjectInstaller, which inherits from Installer. Supõe-se há um executável de serviço que contém dois serviços, "Olá, mundo serviço 1" e "Olá, mundo serviço 2".It is assumed there is a service executable that contains two services, "Hello-World Service 1" and "Hello-World Service 2". Construtor para MyProjectInstaller (que seria chamada pelo utilitário de instalação), ServiceInstaller objetos são criados para cada serviço e um ServiceProcessInstaller é criado para o executável.Within the constructor for MyProjectInstaller (which would be called by the install utility), ServiceInstaller objects are created for each service, and a ServiceProcessInstaller is created for the executable. Para o utilitário de instalação reconhecer MyProjectInstaller como um instalador válido, o RunInstallerAttribute atributo é definido como true.For the install utility to recognize MyProjectInstaller as a valid installer, the RunInstallerAttribute attribute is set to true.

Propriedades opcionais são definidas no instalador do processo e os instaladores do serviço antes dos instaladores são adicionados à Installers coleção.Optional properties are set on the process installer and the service installers before the installers are added to the Installers collection. Quando o utilitário de instalação acessa MyProjectInstaller, os objetos adicionados para o Installers coleção por meio de uma chamada para InstallerCollection.Add serão instalados por sua vez.When the install utility accesses MyProjectInstaller, the objects added to the Installers collection through a call to InstallerCollection.Add will be installed in turn. Durante o processo, o instalador mantém informações de estado que indica quais objetos foram instalados, portanto, cada objeto pode ser revertido por sua vez no caso de uma falha de instalação.During the process, the installer maintains state information indicating which objects have been installed, so each object can be backed out in turn in case of an installation failure.

Normalmente, você não deve instanciar sua classe de instalador de projeto explicitamente.Normally, you would not instantiate your project installer class explicitly. Você deve criá-lo e adicionar o RunInstallerAttribute, mas o utilitário de instalação realmente chama e, portanto, instancia a classe.You would create it and add the RunInstallerAttribute, but the install utility actually calls, and therefore instantiates, the class.

#using <System.dll>
#using <System.ServiceProcess.dll>
#using <System.Configuration.Install.dll>

using namespace System;
using namespace System::Collections;
using namespace System::Configuration::Install;
using namespace System::ServiceProcess;
using namespace System::ComponentModel;

[RunInstaller(true)]
public ref class MyProjectInstaller : public Installer
{
private:
    ServiceInstaller^ serviceInstaller1;
    ServiceInstaller^ serviceInstaller2;
    ServiceProcessInstaller^ processInstaller;

public:
    MyProjectInstaller()
    {
        // Instantiate installers for process and services.
        processInstaller = gcnew ServiceProcessInstaller;
        serviceInstaller1 = gcnew ServiceInstaller;
        serviceInstaller2 = gcnew 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 );
    }

    static void Main()
    {
        Console::WriteLine("Usage: InstallUtil.exe [<service>.exe]");
    }
};

int main()
{
    MyProjectInstaller::Main();
}
using System;
using System.Collections;
using System.Configuration.Install;
using System.ServiceProcess;
using System.ComponentModel;

[RunInstaller(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);
    }

    public static void Main()
    {
        Console.WriteLine("Usage: InstallUtil.exe [<service>.exe]");
    }
}

Imports System
Imports System.Collections
Imports System.Configuration.Install
Imports System.ServiceProcess
Imports System.ComponentModel

<RunInstallerAttribute(True)> _
Public Class MyProjectInstaller
    Inherits Installer
    Private serviceInstaller1 As ServiceInstaller
    Private serviceInstaller2 As ServiceInstaller
    Private processInstaller As ServiceProcessInstaller    
    
    Public Sub New()
        ' Instantiate installers for process and services.
        processInstaller = New ServiceProcessInstaller()
        serviceInstaller1 = New ServiceInstaller()
        serviceInstaller2 = New ServiceInstaller()
        
        ' The services will run under the system account.
        processInstaller.Account = ServiceAccount.LocalSystem
        
        ' The services will be 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)
    End Sub

    Public Shared Sub Main()
        Console.WriteLine("Usage: InstallUtil.exe [<service>.exe]")
    End Sub
End Class

Comentários

O ServiceProcessInstaller funciona comuns a todos os serviços em um executável.The ServiceProcessInstaller does work common to all services in an executable. Ele é usado pelo utilitário de instalação para gravar valores do Registro associados aos serviços que você deseja instalar.It is used by the installation utility to write registry values associated with services you want to install.

Para instalar um serviço, crie uma classe de instalador de projeto que herda de Installere defina o RunInstallerAttribute na classe para true.To install a service, create a project installer class that inherits from Installer, and set the RunInstallerAttribute on the class to true. Dentro de seu projeto, criar uma instância de um ServiceProcessInstaller instância por aplicativo de serviço e um ServiceInstaller instância para cada serviço no aplicativo.Within your project, instantiate one ServiceProcessInstaller instance per service application, and one ServiceInstaller instance for each service in the application. Por fim, adicione a ServiceProcessInstaller instância e o ServiceInstaller instâncias à sua classe de instalador de projeto.Finally, add the ServiceProcessInstaller instance and the ServiceInstaller instances to your project installer class.

Quando InstallUtil.exe é executado, o utilitário procura por classes no assembly de serviço com o RunInstallerAttribute definido como true.When InstallUtil.exe runs, the utility looks for classes in the service assembly with the RunInstallerAttribute set to true. Adicionar classes ao assembly do serviço, adicionando-o Installers coleção associada ao instalador do seu projeto.Add classes to the service assembly by adding them to the Installers collection associated with your project installer. Se RunInstallerAttribute é false, o utilitário de instalação ignora o instalador de projeto.If RunInstallerAttribute is false, the install utility ignores the project installer.

Para uma instância do ServiceProcessInstaller, você pode modificar as propriedades incluem especificando que um aplicativo de serviço executado sob uma conta que não seja o usuário conectado.For an instance of ServiceProcessInstaller, properties you can modify include specifying that a service application run under an account other than the logged-on user. Você pode especificar um determinado Username e Password par sob a qual o serviço deve ser executado, ou você pode usar Account para especificar que o serviço é executado na conta do sistema do computador, local ou conta de serviço de rede ou uma conta de usuário.You can specify a particular Username and Password pair under which the service should run, or you can use Account to specify that the service run under the computer's System account, a local or network service account, or a user account.

Observação

Conta sistema deste computador não é o mesmo que a conta de administrador.The computer's System account is not the same as the Administrator account.

Normalmente, você não chamar métodos em ServiceInstaller dentro de seu código; eles geralmente são chamados apenas pelo utilitário de instalação.Normally, you do not call the methods on ServiceInstaller within your code; they are generally called only by the install utility. O utilitário de instalação chama automaticamente o ServiceProcessInstaller.Install e ServiceInstaller.Install métodos durante o processo de instalação.The install utility automatically calls the ServiceProcessInstaller.Install and ServiceInstaller.Install methods during the installation process. Ele desfaz falhas, se necessário, chamando Rollback (ou ServiceInstaller.Rollback) em todos os componentes instalados anteriormente.It backs out failures, if necessary, by calling Rollback (or ServiceInstaller.Rollback) on all previously installed components.

Rotina de instalação do aplicativo mantém informações automaticamente sobre os componentes já instalado, usando o instalador de projeto Installer.Context.An application's install routine maintains information automatically about the components already installed, using the project installer's Installer.Context. Essas informações de estado são atualizadas continuamente, como o ServiceProcessInstaller instância e cada ServiceInstaller instância é instalada pelo utilitário.This state information is continuously updated as the ServiceProcessInstaller instance and each ServiceInstaller instance is installed by the utility. Não é geralmente necessário para seu código modificar essas informações de estado explicitamente.It is usually unnecessary for your code to modify this state information explicitly.

Criando uma instância de um ServiceProcessInstaller faz com que o construtor de classe base, ComponentInstaller, para ser chamado.Instantiating a ServiceProcessInstaller causes the base class constructor, ComponentInstaller, to be called.

Construtores

ServiceProcessInstaller() ServiceProcessInstaller() ServiceProcessInstaller() ServiceProcessInstaller()

Cria uma nova instância da classe ServiceProcessInstaller.Creates a new instance of the ServiceProcessInstaller class.

Propriedades

Account Account Account Account

Obtém ou define o tipo de conta na qual executar este aplicativo de serviço.Gets or sets the type of account under which to run this service application.

CanRaiseEvents CanRaiseEvents CanRaiseEvents CanRaiseEvents

Obtém um valor que indica se o componente pode acionar um evento.Gets a value indicating whether the component can raise an event.

(Inherited from Component)
Container Container Container Container

Obtém o IContainer que contém o Component.Gets the IContainer that contains the Component.

(Inherited from Component)
Context Context Context Context

Obtém ou define informações sobre a instalação atual.Gets or sets information about the current installation.

(Inherited from Installer)
DesignMode DesignMode DesignMode DesignMode

Obtém um valor que indica se o Component está no modo de design no momento.Gets a value that indicates whether the Component is currently in design mode.

(Inherited from Component)
Events Events Events Events

Obtém a lista de manipuladores de eventos que estão anexados a este Component.Gets the list of event handlers that are attached to this Component.

(Inherited from Component)
HelpText HelpText HelpText HelpText

Obtém o texto de ajuda exibido para opções de instalação do serviço.Gets help text displayed for service installation options.

Installers Installers Installers Installers

Obtém a coleção de instaladores que contém esse instalador.Gets the collection of installers that this installer contains.

(Inherited from Installer)
Parent Parent Parent Parent

Obtém ou define o instalador que contém a coleção à qual o instalador pertence.Gets or sets the installer containing the collection that this installer belongs to.

(Inherited from Installer)
Password Password Password Password

Obtém ou define a senha associada à conta de usuário na qual aplicativo de serviço é executado.Gets or sets the password associated with the user account under which the service application runs.

Site Site Site Site

Obtém ou define o ISite do Component.Gets or sets the ISite of the Component.

(Inherited from Component)
Username Username Username Username

Obtém ou define a conta do usuário na qual aplicativo de serviço será executado.Gets or sets the user account under which the service application will run.

Métodos

Commit(IDictionary) Commit(IDictionary) Commit(IDictionary) Commit(IDictionary)

Quando substituído em uma classe derivada, conclui a transação de instalação.When overridden in a derived class, completes the install transaction.

(Inherited from Installer)
CopyFromComponent(IComponent) CopyFromComponent(IComponent) CopyFromComponent(IComponent) CopyFromComponent(IComponent)

Implementa o método CopyFromComponent(IComponent) da classe base sem nenhum comportamento específico a uma classe de ServiceProcessInstaller.Implements the base class CopyFromComponent(IComponent) method with no ServiceProcessInstaller class-specific behavior.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Cria um objeto que contém todas as informações relevantes necessárias para gerar um proxy usado para se comunicar com um objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose() Dispose() Dispose() Dispose()

Libera todos os recursos usados pelo Component.Releases all resources used by the Component.

(Inherited from Component)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

Libera os recursos não gerenciados usados pelo Component e opcionalmente libera os recursos gerenciados.Releases the unmanaged resources used by the Component and optionally releases the managed resources.

(Inherited from Component)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Recupera o objeto de serviço de tempo de vida atual que controla a política de ciclo de vida para esta instância.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetService(Type) GetService(Type) GetService(Type) GetService(Type)

Retorna um objeto que representa um serviço fornecido pelo Component ou pelo seu Container.Returns an object that represents a service provided by the Component or by its Container.

(Inherited from Component)
GetType() GetType() GetType() GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Obtém um objeto de serviço de tempo de vida para controlar a política de tempo de vida para essa instância.Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
Install(IDictionary) Install(IDictionary) Install(IDictionary) Install(IDictionary)

Grava informações do aplicativo de serviço no Registro.Writes service application information to the registry. Este método destina-se a ser usado por ferramentas de instalação, que chamam automaticamente os métodos apropriados.This method is meant to be used by installation tools, which call the appropriate methods automatically.

IsEquivalentInstaller(ComponentInstaller) IsEquivalentInstaller(ComponentInstaller) IsEquivalentInstaller(ComponentInstaller) IsEquivalentInstaller(ComponentInstaller)

Determina se o instalador especificado instala o mesmo objeto como este instalador.Determines if the specified installer installs the same object as this installer.

(Inherited from ComponentInstaller)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Cria uma cópia superficial do objeto MarshalByRefObject atual.Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
OnAfterInstall(IDictionary) OnAfterInstall(IDictionary) OnAfterInstall(IDictionary) OnAfterInstall(IDictionary)

Aciona o evento AfterInstall.Raises the AfterInstall event.

(Inherited from Installer)
OnAfterRollback(IDictionary) OnAfterRollback(IDictionary) OnAfterRollback(IDictionary) OnAfterRollback(IDictionary)

Aciona o evento AfterRollback.Raises the AfterRollback event.

(Inherited from Installer)
OnAfterUninstall(IDictionary) OnAfterUninstall(IDictionary) OnAfterUninstall(IDictionary) OnAfterUninstall(IDictionary)

Aciona o evento AfterUninstall.Raises the AfterUninstall event.

(Inherited from Installer)
OnBeforeInstall(IDictionary) OnBeforeInstall(IDictionary) OnBeforeInstall(IDictionary) OnBeforeInstall(IDictionary)

Aciona o evento BeforeInstall.Raises the BeforeInstall event.

(Inherited from Installer)
OnBeforeRollback(IDictionary) OnBeforeRollback(IDictionary) OnBeforeRollback(IDictionary) OnBeforeRollback(IDictionary)

Aciona o evento BeforeRollback.Raises the BeforeRollback event.

(Inherited from Installer)
OnBeforeUninstall(IDictionary) OnBeforeUninstall(IDictionary) OnBeforeUninstall(IDictionary) OnBeforeUninstall(IDictionary)

Aciona o evento BeforeUninstall.Raises the BeforeUninstall event.

(Inherited from Installer)
OnCommitted(IDictionary) OnCommitted(IDictionary) OnCommitted(IDictionary) OnCommitted(IDictionary)

Aciona o evento Committed.Raises the Committed event.

(Inherited from Installer)
OnCommitting(IDictionary) OnCommitting(IDictionary) OnCommitting(IDictionary) OnCommitting(IDictionary)

Aciona o evento Committing.Raises the Committing event.

(Inherited from Installer)
Rollback(IDictionary) Rollback(IDictionary) Rollback(IDictionary) Rollback(IDictionary)

Reverte informações de aplicativo de serviço gravadas no Registro pelo procedimento de instalação.Rolls back service application information written to the registry by the installation procedure. Este método destina-se a ser usado pelas ferramentas de instalação, que processam os métodos apropriados automaticamente.This method is meant to be used by installation tools, which process the appropriate methods automatically.

ToString() ToString() ToString() ToString()

Retorna um String que contém o nome do Component, se houver.Returns a String containing the name of the Component, if any. Esse método não deve ser substituído.This method should not be overridden.

(Inherited from Component)
Uninstall(IDictionary) Uninstall(IDictionary) Uninstall(IDictionary) Uninstall(IDictionary)

Quando substituído em uma classe derivada, remove uma instalação.When overridden in a derived class, removes an installation.

(Inherited from Installer)

Eventos

AfterInstall AfterInstall AfterInstall AfterInstall

Ocorre depois que os métodos do Install(IDictionary) de todos os instaladores na propriedade Installers foram executados.Occurs after the Install(IDictionary) methods of all the installers in the Installers property have run.

(Inherited from Installer)
AfterRollback AfterRollback AfterRollback AfterRollback

Ocorre após as instalações de todos os instaladores na propriedade Installers serem revertidas.Occurs after the installations of all the installers in the Installers property are rolled back.

(Inherited from Installer)
AfterUninstall AfterUninstall AfterUninstall AfterUninstall

Ocorre depois que todos os instaladores na propriedade Installers realizam suas operações de desinstalação.Occurs after all the installers in the Installers property perform their uninstallation operations.

(Inherited from Installer)
BeforeInstall BeforeInstall BeforeInstall BeforeInstall

Ocorre antes do método Install(IDictionary) de cada instalador no instalador em que a coleção foi executada.Occurs before the Install(IDictionary) method of each installer in the installer collection has run.

(Inherited from Installer)
BeforeRollback BeforeRollback BeforeRollback BeforeRollback

Ocorre antes que os instaladores na propriedade Installers sejam revertidos.Occurs before the installers in the Installers property are rolled back.

(Inherited from Installer)
BeforeUninstall BeforeUninstall BeforeUninstall BeforeUninstall

Ocorre antes dos instaladores na propriedade Installers executarem suas operações de desinstalação.Occurs before the installers in the Installers property perform their uninstall operations.

(Inherited from Installer)
Committed Committed Committed Committed

Ocorre depois que todos os instaladores na propriedade Installers confirmaram suas instalações.Occurs after all the installers in the Installers property have committed their installations.

(Inherited from Installer)
Committing Committing Committing Committing

Ocorre antes que os instaladores na propriedade Installers façam commit de suas instalações.Occurs before the installers in the Installers property commit their installations.

(Inherited from Installer)
Disposed Disposed Disposed Disposed

Ocorre quando o componente é disposto por uma chamada para o método Dispose().Occurs when the component is disposed by a call to the Dispose() method.

(Inherited from Component)

Aplica-se a

Veja também