Procédure : héberger un service WCF dans un service Windows managéHow to: Host a WCF Service in a Managed Windows Service

Cette rubrique décrit les étapes de base requises pour créer un service Windows Communication Foundation (WCF) qui est hébergé par un Service Windows.This topic outlines the basic steps required to create a Windows Communication Foundation (WCF) service that is hosted by a Windows Service. Le scénario est activé par le service Windows managé qui héberge l’option est un service WCF de longs hébergé en dehors d’Internet Information Services (IIS) dans un environnement sécurisé qui n’est pas activé de message.The scenario is enabled by the managed Windows service hosting option that is a long-running WCF service hosted outside of Internet Information Services (IIS) in a secure environment that is not message activated. La durée de vie du service est contrôlée par le système d'exploitation.The lifetime of the service is controlled instead by the operating system. Cette option d'hébergement est disponible dans toutes les versions de Windows.This hosting option is available in all versions of Windows.

Les services Windows peuvent être gérés avec Microsoft.ManagementConsole.SnapIn dans MMC (Microsoft Management Console) et peuvent être configurés pour démarrer automatiquement lorsque le système démarre.Windows services can be managed with the Microsoft.ManagementConsole.SnapIn in Microsoft Management Console (MMC) and can be configured to start up automatically when the system boots up. Cette option d’hébergement consiste à enregistrer le domaine d’application (AppDomain) qui héberge un service WCF en tant qu’un service Windows managé afin que la durée de vie du processus du service est contrôlée par le Gestionnaire de contrôle de services (SCM) pour les services de Windows.This hosting option consists of registering the application domain (AppDomain) that hosts a WCF service as a managed Windows service so that the process lifetime of the service is controlled by the Service Control Manager (SCM) for Windows services.

Le code du service inclut l'implémentation du contrat de service, d'une classe de service Windows et d'une classe Installer.The service code includes a service implementation of the service contract, a Windows Service class, and an installer class. La classe d’implémentation, CalculatorService, est un service WCF.The service implementation class, CalculatorService, is a WCF service. Le CalculatorWindowsService est un service Windows.The CalculatorWindowsService is a Windows service. Pour prétendre au titre de service Windows, la classe hérite de la ServiceBase et implémente les méthodes OnStart et OnStop.To qualify as a Windows service, the class inherits from ServiceBase and implements the OnStart and OnStop methods. Dans la méthode OnStart, un objet ServiceHost est créé pour le type CalculatorService et est ouvert.In OnStart, a ServiceHost is created for the CalculatorService type and opened. Dans la méthode OnStop, le service est arrêté et éliminé.In OnStop, the service is stopped and disposed. L'hôte est également chargé de fournir une adresse de base à l'hôte de service, qui a été configuré dans les paramètres d'application.The host is also responsible for providing a base address to the service host, which has been configured in application settings. La classe Installer, qui hérite de Installer, permet à l'outil Installutil.exe d'installer le programme comme un service Windows.The installer class, which inherits from Installer, allows the program to be installed as a Windows service by the Installutil.exe tool.

Construction du service et ajout du code d'hébergementConstruct the service and provide the hosting code

  1. Créer un nouveau Visual Studio application Console projet appelé Service.Create a new Visual Studio Console app project called Service.

  2. Renommez Program.cs en Service.cs.Rename Program.cs to Service.cs.

  3. Modifier l’espace de noms Microsoft.ServiceModel.Samples.Change the namespace to Microsoft.ServiceModel.Samples.

  4. Ajoutez des références aux assemblys suivants :Add references to the following assemblies:

    • System.ServiceModel.dllSystem.ServiceModel.dll

    • System.ServiceProcess.dllSystem.ServiceProcess.dll

    • System.Configuration.Install.dllSystem.Configuration.Install.dll

  5. Ajoutez les instructions using suivantes à Service.cs.Add the following using statements to Service.cs.

    using System.ComponentModel;
    using System.ServiceModel;
    using System.ServiceProcess;
    using System.Configuration;
    using System.Configuration.Install;
    
    Imports System.ComponentModel
    Imports System.ServiceModel
    Imports System.ServiceProcess
    Imports System.Configuration
    Imports System.Configuration.Install
    
  6. Définissez le contrat de service ICalculator, tel qu'indiqué dans le code suivant.Define the ICalculator service contract as shown in the following code.

    // Define a service contract.
    [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
    public interface ICalculator
    {
        [OperationContract]
        double Add(double n1, double n2);
        [OperationContract]
        double Subtract(double n1, double n2);
        [OperationContract]
        double Multiply(double n1, double n2);
        [OperationContract]
        double Divide(double n1, double n2);
    }
    
    ' Define a service contract.
    <ServiceContract(Namespace:="http://Microsoft.ServiceModel.Samples")> _
    Public Interface ICalculator
        <OperationContract()> _
        Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double
        <OperationContract()> _
        Function Subtract(ByVal n1 As Double, ByVal n2 As Double) As Double
        <OperationContract()> _
        Function Multiply(ByVal n1 As Double, ByVal n2 As Double) As Double
        <OperationContract()> _
        Function Divide(ByVal n1 As Double, ByVal n2 As Double) As Double
    End Interface
    
  7. Implémentez le contrat de service dans une classe appelée CalculatorService, tel qu'indiqué dans le code suivant.Implement the service contract in a class called CalculatorService as shown in the following code.

    // Implement the ICalculator service contract in a service class.
    public class CalculatorService : ICalculator
    {
        // Implement the ICalculator methods.
        public double Add(double n1, double n2)
        {
            double result = n1 + n2;
            return result;
        }
    
        public double Subtract(double n1, double n2)
        {
            double result = n1 - n2;
            return result;
        }
    
        public double Multiply(double n1, double n2)
        {
            double result = n1 * n2;
            return result;
        }
    
        public double Divide(double n1, double n2)
        {
            double result = n1 / n2;
            return result;
        }
    }
    
    ' Implement the ICalculator service contract in a service class.
    Public Class CalculatorService
        Implements ICalculator
        ' Implement the ICalculator methods.
        Public Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Add
            Return n1 + n2
    
        End Function
    
        Public Function Subtract(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Subtract
            Return n1 - n2
    
        End Function
    
        Public Function Multiply(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Multiply
            Return n1 * n2
        End Function
    
        Public Function Divide(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Divide
            Return n1 / n2
    
        End Function
    End Class
    
  8. Créez une classe appelée CalculatorWindowsService qui hérite de la classe ServiceBase.Create a new class called CalculatorWindowsService that inherits from the ServiceBase class. Ajoutez une variable locale appelée serviceHost pour faire référence à l'instance ServiceHost.Add a local variable called serviceHost to reference the ServiceHost instance. Définissez la méthode Main qui appelle ServiceBase.Run(new CalculatorWindowsService)Define the Main method that calls ServiceBase.Run(new CalculatorWindowsService)

    public class CalculatorWindowsService : ServiceBase
    {
        public ServiceHost serviceHost = null;
        public CalculatorWindowsService()
        {
            // Name the Windows Service
            ServiceName = "WCFWindowsServiceSample";
        }
    
        public static void Main()
        {
            ServiceBase.Run(new CalculatorWindowsService());
        }
    
    Public Class CalculatorWindowsService
        Inherits ServiceBase
        Public serviceHost As ServiceHost = Nothing
        Public Sub New()
            ' Name the Windows Service
            ServiceName = "WCFWindowsServiceSample"
        End Sub
    
        Public Shared Sub Main()
            ServiceBase.Run(New CalculatorWindowsService())
        End Sub
    
  9. Substituez la méthode OnStart(String[]) en créant et en ouvrant une nouvelle instance ServiceHost, comme illustré dans le code suivant.Override the OnStart(String[]) method by creating and opening a new ServiceHost instance as shown in the following code.

    // Start the Windows service.
    protected override void OnStart(string[] args)
    {
        if (serviceHost != null)
        {
            serviceHost.Close();
        }
    
        // Create a ServiceHost for the CalculatorService type and 
        // provide the base address.
        serviceHost = new ServiceHost(typeof(CalculatorService));
    
        // Open the ServiceHostBase to create listeners and start 
        // listening for messages.
        serviceHost.Open();
    }
    
    ' Start the Windows service.
    Protected Overrides Sub OnStart(ByVal args() As String)
        If serviceHost IsNot Nothing Then
            serviceHost.Close()
        End If
    
        ' Create a ServiceHost for the CalculatorService type and 
        ' provide the base address.
        serviceHost = New ServiceHost(GetType(CalculatorService))
    
        ' Open the ServiceHostBase to create listeners and start 
        ' listening for messages.
        serviceHost.Open()
    End Sub
    
  10. Substituez la méthode OnStop fermant ServiceHost, comme illustré dans le code suivant.Override the OnStop method closing the ServiceHost as shown in the following code.

    protected override void OnStop()
    {
        if (serviceHost != null)
        {
            serviceHost.Close();
            serviceHost = null;
        }
    }
    
    Protected Overrides Sub OnStop()
        If serviceHost IsNot Nothing Then
            serviceHost.Close()
            serviceHost = Nothing
        End If
    End Sub
    
  11. Créez une classe appelée ProjectInstaller qui hérite de Installer et qui est marquée avec RunInstallerAttribute défini avec la valeur true.Create a new class called ProjectInstaller that inherits from Installer and that is marked with the RunInstallerAttribute set to true. Cela permet au service Windows d'être installé par l'outil Installutil.exe.This allows the Windows service to be installed by the Installutil.exe tool.

    // Provide the ProjectInstaller class which allows 
    // the service to be installed by the Installutil.exe tool
    [RunInstaller(true)]
    public class ProjectInstaller : Installer
    {
        private ServiceProcessInstaller process;
        private ServiceInstaller service;
    
        public ProjectInstaller()
        {
            process = new ServiceProcessInstaller();
            process.Account = ServiceAccount.LocalSystem;
            service = new ServiceInstaller();
            service.ServiceName = "WCFWindowsServiceSample";
            Installers.Add(process);
            Installers.Add(service);
        }
    }
    
       ' Provide the ProjectInstaller class which allows 
       ' the service to be installed by the Installutil.exe tool
       <RunInstaller(True)> _
    Public Class ProjectInstaller
           Inherits Installer
           Private process As ServiceProcessInstaller
           Private service As ServiceInstaller
    
           Public Sub New()
               process = New ServiceProcessInstaller()
               process.Account = ServiceAccount.LocalSystem
               service = New ServiceInstaller()
               service.ServiceName = "WCFWindowsServiceSample"
               Installers.Add(process)
               Installers.Add(service)
           End Sub
       End Class
    
  12. Supprimez la classe Service qui a été générée lors de la création du projet.Remove the Service class that was generated when you created the project.

  13. Ajoutez un fichier de configuration d'application au projet.Add an application configuration file to the project. Remplacez le contenu du fichier par le fichier XML de configuration suivant.Replace the contents of the file with the following configuration XML.

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <system.serviceModel>    <services>
          <!-- This section is optional with the new configuration model
               introduced in .NET Framework 4. -->
          <service name="Microsoft.ServiceModel.Samples.CalculatorService"
                   behaviorConfiguration="CalculatorServiceBehavior">
            <host>
              <baseAddresses>
                <add baseAddress="http://localhost:8000/ServiceModelSamples/service"/>
              </baseAddresses>
            </host>
            <!-- this endpoint is exposed at the base address provided by host: http://localhost:8000/ServiceModelSamples/service  -->
            <endpoint address=""
                      binding="wsHttpBinding"
                      contract="Microsoft.ServiceModel.Samples.ICalculator" />
            <!-- the mex endpoint is exposed at http://localhost:8000/ServiceModelSamples/service/mex -->
            <endpoint address="mex"
                      binding="mexHttpBinding"
                      contract="IMetadataExchange" />
          </service>
        </services>
        <behaviors>
          <serviceBehaviors>
            <behavior name="CalculatorServiceBehavior">
              <serviceMetadata httpGetEnabled="true"/>
              <serviceDebug includeExceptionDetailInFaults="False"/>
            </behavior>
          </serviceBehaviors>
        </behaviors>
      </system.serviceModel>
    </configuration>
    

    Cliquez avec le bouton droit sur le fichier App.config dans le l’Explorateur de solutions et sélectionnez propriétés.Right click the App.config file in the Solution Explorer and select Properties. Sous Copy to Output Directory sélectionnez Copier si plus récent.Under Copy to Output Directory select Copy if Newer.

    L'exemple spécifie explicitement les points de terminaison dans le fichier de configuration.This example explicitly specifies endpoints in the configuration file. Si vous n'ajoutez pas de points de terminaison au service, le runtime ajoute les points de terminaison par défaut.If you do not add any endpoints to the service, the runtime adds default endpoints for you. Dans cet exemple, étant donné que le service a un ServiceMetadataBehavior défini sur la valeur true, la publication des métadonnées est également activée pour votre service.In this example, because the service has a ServiceMetadataBehavior set to true, your service also has publishing metadata enabled. Pour plus d’informations sur les points de terminaison, les liaisons et les comportements par défaut, consultez Configuration simplifiée et Configuration simplifiée pour les services WCF.For more information about default endpoints, bindings, and behaviors, see Simplified Configuration and Simplified Configuration for WCF Services.

Démarrez et exécutez le service.Install and run the service

  1. Générez la solution pour créer l'exécutable Service.exe.Build the solution to create the Service.exe executable.

  2. Ouvrez l’invite de commandes développeur pour Visual Studio et accédez au répertoire du projet.Open Developer Command Prompt for Visual Studio and navigate to the project directory. Pour installer le service Windows, tapez installutil bin\service.exe à l'invite de commandes.Type installutil bin\service.exe at the command prompt to install the Windows service.

    Tapez services.msc à l'invite de commandes pour accéder au Gestionnaire de contrôle des services (SCM).Type services.msc at the command prompt to access the Service Control Manager (SCM). Le service Windows doit apparaître dans les services comme « WCFWindowsServiceSample ».The Windows service should appear in Services as "WCFWindowsServiceSample". Le service WCF peut répondre aux clients uniquement si le service Windows est en cours d’exécution.The WCF service can only respond to clients if the Windows service is running. Pour démarrer le service, faites un clic droit dans le SCM et sélectionnez « Start » ou type net start WCFWindowsServiceSample à l’invite de commandes.To start the service, right-click it in the SCM and select "Start", or type net start WCFWindowsServiceSample at the command prompt.

  3. Si vous apportez des modifications au service, vous devez d'abord l'arrêter et le désinstaller.If you make changes to the service, you must first stop it and uninstall it. Pour arrêter le service, cliquez sur le service dans le GCL et sélectionnez « Arrêter » ou stop net de type WCFWindowsServiceSample à l’invite de commandes.To stop the service, right-click the service in the SCM and select "Stop", or type net stop WCFWindowsServiceSample at the command prompt. Notez que si vous arrêtez le service Windows puis exécutez un client, une exception EndpointNotFoundException se produit lorsqu'un client tente d'accéder au service.Note that if you stop the Windows service and then run a client, an EndpointNotFoundException exception occurs when a client attempts to access the service. Pour désinstaller le type de service Windows installutil /u bin\service.exe à l’invite de commandes.To uninstall the Windows service type installutil /u bin\service.exe at the command prompt.

ExempleExample

Voici une liste complète du code utilisé dans cette rubrique :The following is a complete listing of the code used by this topic:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

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

namespace Microsoft.ServiceModel.Samples
{
    // Define a service contract.
    [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
    public interface ICalculator
    {
        [OperationContract]
        double Add(double n1, double n2);
        [OperationContract]
        double Subtract(double n1, double n2);
        [OperationContract]
        double Multiply(double n1, double n2);
        [OperationContract]
        double Divide(double n1, double n2);
    }

    // Implement the ICalculator service contract in a service class.
    public class CalculatorService : ICalculator
    {
        // Implement the ICalculator methods.
        public double Add(double n1, double n2)
        {
            double result = n1 + n2;
            return result;
        }

        public double Subtract(double n1, double n2)
        {
            double result = n1 - n2;
            return result;
        }

        public double Multiply(double n1, double n2)
        {
            double result = n1 * n2;
            return result;
        }

        public double Divide(double n1, double n2)
        {
            double result = n1 / n2;
            return result;
        }
    }

    public class CalculatorWindowsService : ServiceBase
    {
        public ServiceHost serviceHost = null;
        public CalculatorWindowsService()
        {
            // Name the Windows Service
            ServiceName = "WCFWindowsServiceSample";
        }

        public static void Main()
        {
            ServiceBase.Run(new CalculatorWindowsService());
        }

        // Start the Windows service.
        protected override void OnStart(string[] args)
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
            }

            // Create a ServiceHost for the CalculatorService type and 
            // provide the base address.
            serviceHost = new ServiceHost(typeof(CalculatorService));

            // Open the ServiceHostBase to create listeners and start 
            // listening for messages.
            serviceHost.Open();
        }

        protected override void OnStop()
        {
            if (serviceHost != null)
            {
                serviceHost.Close();
                serviceHost = null;
            }
        }
    }

    // Provide the ProjectInstaller class which allows 
    // the service to be installed by the Installutil.exe tool
    [RunInstaller(true)]
    public class ProjectInstaller : Installer
    {
        private ServiceProcessInstaller process;
        private ServiceInstaller service;

        public ProjectInstaller()
        {
            process = new ServiceProcessInstaller();
            process.Account = ServiceAccount.LocalSystem;
            service = new ServiceInstaller();
            service.ServiceName = "WCFWindowsServiceSample";
            Installers.Add(process);
            Installers.Add(service);
        }
    }
}
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text

Imports System.ComponentModel
Imports System.ServiceModel
Imports System.ServiceProcess
Imports System.Configuration
Imports System.Configuration.Install

Namespace Microsoft.ServiceModel.Samples
    ' Define a service contract.
    <ServiceContract(Namespace:="http://Microsoft.ServiceModel.Samples")> _
    Public Interface ICalculator
        <OperationContract()> _
        Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double
        <OperationContract()> _
        Function Subtract(ByVal n1 As Double, ByVal n2 As Double) As Double
        <OperationContract()> _
        Function Multiply(ByVal n1 As Double, ByVal n2 As Double) As Double
        <OperationContract()> _
        Function Divide(ByVal n1 As Double, ByVal n2 As Double) As Double
    End Interface

    ' Implement the ICalculator service contract in a service class.
    Public Class CalculatorService
        Implements ICalculator
        ' Implement the ICalculator methods.
        Public Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Add
            Return n1 + n2

        End Function

        Public Function Subtract(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Subtract
            Return n1 - n2

        End Function

        Public Function Multiply(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Multiply
            Return n1 * n2
        End Function

        Public Function Divide(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Divide
            Return n1 / n2

        End Function
    End Class

    Public Class CalculatorWindowsService
        Inherits ServiceBase
        Public serviceHost As ServiceHost = Nothing
        Public Sub New()
            ' Name the Windows Service
            ServiceName = "WCFWindowsServiceSample"
        End Sub

        Public Shared Sub Main()
            ServiceBase.Run(New CalculatorWindowsService())
        End Sub

        ' Start the Windows service.
        Protected Overrides Sub OnStart(ByVal args() As String)
            If serviceHost IsNot Nothing Then
                serviceHost.Close()
            End If

            ' Create a ServiceHost for the CalculatorService type and 
            ' provide the base address.
            serviceHost = New ServiceHost(GetType(CalculatorService))

            ' Open the ServiceHostBase to create listeners and start 
            ' listening for messages.
            serviceHost.Open()
        End Sub

        Protected Overrides Sub OnStop()
            If serviceHost IsNot Nothing Then
                serviceHost.Close()
                serviceHost = Nothing
            End If
        End Sub
    End Class
    ' Provide the ProjectInstaller class which allows 
    ' the service to be installed by the Installutil.exe tool
    <RunInstaller(True)> _
 Public Class ProjectInstaller
        Inherits Installer
        Private process As ServiceProcessInstaller
        Private service As ServiceInstaller

        Public Sub New()
            process = New ServiceProcessInstaller()
            process.Account = ServiceAccount.LocalSystem
            service = New ServiceInstaller()
            service.ServiceName = "WCFWindowsServiceSample"
            Installers.Add(process)
            Installers.Add(service)
        End Sub
    End Class
End Namespace

Comme pour l'option d'auto-hébergement, l'environnement d'hébergement du service Windows requiert que le code d'hébergement soit écrit dans le cadre de l'application.Like the "Self-Hosting" option, the Windows service hosting environment requires that some hosting code be written as part of the application. Le service est implémenté en tant qu'application console et contient son propre code d'hébergement.The service is implemented as a console application and contains its own hosting code. Dans d'autres environnements d'hébergement, tels que le service d'activation des processus Windows (WAS) dans les services IIS (Internet Information Services), il n'est pas nécessaire que les développeurs écrivent le code d'hébergement.In other hosting environments, such as Windows Process Activation Service (WAS) hosting in Internet Information Services (IIS), it is not necessary for developers to write hosting code.

Voir aussiSee also