Pregunta

¿Cómo iniciar automáticamente un servicio después de ejecutar una instalación desde un proyecto de instalación de Visual Studio?

Me acabo de dar cuenta de esto y pensé en compartir la respuesta por el bien general. Respuesta para seguir. Estoy abierto a otras y mejores formas de hacerlo.

¿Fue útil?

Solución

Agregue la siguiente clase a su proyecto.

using System.ServiceProcess;  

class ServInstaller : ServiceInstaller
{
    protected override void OnCommitted(System.Collections.IDictionary savedState)
    {
        ServiceController sc = new ServiceController("YourServiceNameGoesHere");
        sc.Start();
    }
}

El Proyecto de instalación recogerá la clase y ejecutará su servicio una vez que finalice el instalador.

Otros consejos

Pequeña adición a la respuesta aceptada:

También puede obtener el nombre del servicio de esta manera, evitando cualquier problema si el nombre del servicio se cambia en el futuro:

protected override void OnCommitted(System.Collections.IDictionary savedState)
{
    new ServiceController(serviceInstaller1.ServiceName).Start();
}

(Cada instalador tiene un ServiceProcessInstaller y un ServiceInstaller. Aquí el ServiceInstaller se llama serviceInstaller1.)

Este enfoque utiliza la clase de instalador y la menor cantidad de código.

using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;

namespace MyProject
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : Installer
    {
        public ProjectInstaller()
        {
            InitializeComponent();
            serviceInstaller1.AfterInstall += (sender, args) => new ServiceController(serviceInstaller1.ServiceName).Start();
        }
    }
}

Defina serviceInstaller1 (escriba ServiceInstaller) en el diseñador de clases del instalador y también establezca su propiedad ServiceName en el diseñador.

gracias, funciona bien ...

private System.ServiceProcess.ServiceInstaller serviceInstaller1;

private void serviceInstaller1_AfterInstall(object sender, InstallEventArgs e)
{
    ServiceController sc = new ServiceController("YourServiceName");
    sc.Start();
}

En lugar de crear su propia clase, seleccione el instalador de servicios en el instalador del proyecto y agregue un controlador de eventos al evento Comit:

private void serviceInstallerService1_Committed(object sender, InstallEventArgs e)
{
    var serviceInstaller = sender as ServiceInstaller;
    // Start the service after it is installed.
    if (serviceInstaller != null && serviceInstaller.StartType == ServiceStartMode.Automatic)
    {
        var serviceController = new ServiceController(serviceInstaller.ServiceName);
        serviceController.Start();
    }
}

Comenzará su servicio solo si el tipo de inicio está configurado en automático.

Según los fragmentos anteriores, mi archivo ProjectInstaller.cs terminó luciendo así para un servicio llamado FSWServiceMgr.exe. El servicio comenzó después de la instalación. Como nota al margen, recuerde hacer clic en la pestaña Propiedades (no hacer clic con el botón derecho) cuando se selecciona el proyecto de configuración en el Explorador de soluciones para configurar la empresa, etc.


using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;

namespace FSWManager {
    [RunInstaller(true)]
    public partial class ProjectInstaller : Installer {
        public ProjectInstaller() {
            InitializeComponent();
            this.FSWServiceMgr.AfterInstall += FSWServiceMgr_AfterInstall;
        }

        static void FSWServiceMgr_AfterInstall(object sender, InstallEventArgs e) {
            new ServiceController("FSWServiceMgr").Start();
        }
    }
}

También hay otra forma que no involucra código. Puede utilizar la tabla de control de servicio. Edite el archivo msi generado con orca.exe y agregue una entrada a ServiceControl Table .

Solo las columnas ServiceControl, Name, Event y Component_ son obligatorias. La columna Component_ contiene el ComponentId de la tabla de archivos. (Seleccione el archivo en la tabla de archivos y copie el Component_value a la tabla ServiceControl).

El último paso es actualizar el valor de StartServices a 6575 en la tabla InstallExecutesequence. Esto es suficiente para iniciar el servicio.

Por cierto, la tabla de instalación del servicio le permite configurar el instalador para instalar el servicio de Windows.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top