Gewusst wie: Hosten eines WCF-Diensts in einem verwalteten Windows-DienstHow to: Host a WCF Service in a Managed Windows Service

Dieses Thema beschreibt die grundlegenden Schritte zum Erstellen eines Windows Communication Foundation (WCF)-Diensts, das von einem Windows-Dienst gehostet wird.This topic outlines the basic steps required to create a Windows Communication Foundation (WCF) service that is hosted by a Windows Service. Das Szenario wird durch die Hostingoption ist ein langer WCF-Dienst außerhalb von IIS (Internetinformationsdienste) gehostet, in einer sicheren Umgebung, die nicht Nachricht aktiviert ist, die den verwalteten Windows-Dienst aktiviert.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. Die Lebensdauer des Diensts wird stattdessen vom Betriebssystem gesteuert.The lifetime of the service is controlled instead by the operating system. Diese Hostingoption ist in allen Windows-Versionen verfügbar.This hosting option is available in all versions of Windows.

Windows-Dienste können mit Microsoft.ManagementConsole.SnapIn in Microsoft Management Console (MMC) verwaltet und so konfiguriert werden, dass sie beim Systemstart automatisch gestartet werden.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. Diese Hostingoption besteht in der Registrierung der Anwendungsdomäne (AppDomain), die einen WCF-Dienst als verwalteten Windows-Dienst hostet, sodass die Prozesslebensdauer des Diensts durch den Dienststeuerungs-Manager (SCM) für Windows-Dienste gesteuert wird.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.

Der Dienstcode enthält eine Dienstimplementierung des Dienstvertrags, eine Windows-Dienstklasse und eine Installerklasse.The service code includes a service implementation of the service contract, a Windows Service class, and an installer class. Die Dienstimplementierungsklasse, CalculatorService, ist ein WCF-Dienst.The service implementation class, CalculatorService, is a WCF service. CalculatorWindowsService ist ein Windows-Dienst.The CalculatorWindowsService is a Windows service. Damit sich die Klasse als Windows-Dienst eignet, erbt sie von ServiceBase und implementiert die OnStart-Methode und die OnStop-Methode.To qualify as a Windows service, the class inherits from ServiceBase and implements the OnStart and OnStop methods. In OnStart wird ServiceHost für den CalculatorService-Typ erstellt und geöffnet.In OnStart, a ServiceHost is created for the CalculatorService type and opened. In OnStop wird der Dienst beendet und verworfen.In OnStop, the service is stopped and disposed. Der Host ist außerdem für die Bereitstellung einer Basisadresse für den Diensthost verantwortlich, die in den Anwendungseinstellungen konfiguriert wurde.The host is also responsible for providing a base address to the service host, which has been configured in application settings. Durch die Installerklasse, die von Installer erbt, kann das Programm mit dem Tool "Installutil.exe" als Windows-Dienst installiert werden.The installer class, which inherits from Installer, allows the program to be installed as a Windows service by the Installutil.exe tool.

Erstellen des Diensts und Bereitstellen des HostcodesConstruct the service and provide the hosting code

  1. Erstellen Sie ein neues Visual Studio-Konsolenanwendungsprojekt namens "Service".Create a new Visual Studio Console Application project called "Service".

  2. Benennen Sie "Program.cs" in "Service.cs" um.Rename Program.cs to Service.cs.

  3. Ändern Sie den Namespace in "Microsoft.ServiceModel.Samples".Change the namespace to Microsoft.ServiceModel.Samples.

  4. Fügen Sie Verweise auf die folgenden Assemblys hinzu.Add references to the following assemblies.

    • System.ServiceModel.dllSystem.ServiceModel.dll

    • System.ServiceProcess.dllSystem.ServiceProcess.dll

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

  5. Fügen Sie der Datei "Service.cs" die folgenden using-Anweisungen hinzu.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. Definieren Sie den ICalculator-Dienstvertrag, wie im folgenden Code gezeigt.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. Implementieren Sie den Dienstvertrag in einer Klasse namens CalculatorService, wie im folgenden Code gezeigt.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. Erstellen Sie eine neue Klasse namens CalculatorWindowsService, die von der ServiceBase-Klasse erbt.Create a new class called CalculatorWindowsService that inherits from the ServiceBase class. Fügen Sie eine lokale Variable namens serviceHost hinzu, die auf die ServiceHost-Instanz verweist.Add a local variable called serviceHost to reference the ServiceHost instance. Definieren Sie die Main-Methode, die ServiceBase.Run(new CalculatorWindowsService) aufruft.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. Überschreiben Sie die OnStart(String[])-Methode, indem Sie eine neue ServiceHost-Instanz erstellen und öffnen, wie im folgenden Code gezeigt.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. Überschreiben Sie die OnStop-Methode, indem Sie ServiceHost schließen, wie im folgenden Code gezeigt.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. Erstellen Sie eine neue Klasse namens ProjectInstaller, die von Installer erbt und die mit dem auf RunInstallerAttribute festgelegten true gekennzeichnet ist.Create a new class called ProjectInstaller that inherits from Installer and that is marked with the RunInstallerAttribute set to true. Dies ermöglicht die Installation des Tools "Installutil.exe" durch den Windows-Dienst.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. Entfernen Sie die Service-Klasse, die beim Erstellen des Projekts generiert wurde.Remove the Service class that was generated when you created the project.

  13. Fügen Sie dem Projekt eine Anwendungskonfigurationsdatei hinzu.Add an application configuration file to the project. Ersetzen Sie den Inhalt der Datei durch das folgende Konfigurations-XML.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>  
    

    Klicken Sie mit der mit der rechten Maustaste auf die Datei "App.config" in der Projektmappen-Explorer , und wählen Sie Eigenschaften.Right click the App.config file in the Solution Explorer and select Properties. Klicken Sie unter in Ausgabeverzeichnis kopieren wählen kopieren, wenn neuer.Under Copy to Output Directory select Copy if Newer.

    In diesem Beispiel werden die Endpunkte in der Konfigurationsdatei explizit angegeben.This example explicitly specifies endpoints in the configuration file. Wenn Sie dem Dienst keine Endpunkte hinzufügen, werden von der Runtime automatisch Standardendpunkte hinzugefügt.If you do not add any endpoints to the service, the runtime adds default endpoints for you. Da in diesem Beispiel das ServiceMetadataBehavior des Diensts auf true festgelegt ist, ist für den Dienst auch die Veröffentlichung von Metadaten aktiviert.In this example, because the service has a ServiceMetadataBehavior set to true, your service also has publishing metadata enabled. Weitere Informationen zu Standardendpunkten, Bindungen und Verhaltensweisen finden Sie unter vereinfachte Konfiguration und vereinfachte Konfiguration für WCF-Dienste.For more information about default endpoints, bindings, and behaviors, see Simplified Configuration and Simplified Configuration for WCF Services.

Installieren Sie den Dienst, und führen Sie ihn aus.Install and run the service

  1. Erstellen Sie die Projektmappe, um Service.exe zu erstellen.Build the solution to create the Service.exe executable.

  2. Öffnen Sie das Visual Studio 2012Visual Studio 2012-Eingabeaufforderungsfenster, und navigieren Sie zum Projektverzeichnis.Open the Visual Studio 2012Visual Studio 2012 command prompt and navigate to the project directory. Geben Sie an der Eingabeaufforderung installutil bin\service.exe ein, um den Windows-Dienst zu installieren.Type installutil bin\service.exe at the command prompt to install the Windows service.

    Hinweis

    Wenn Sie nicht verwenden die Visual Studio 2012Visual Studio 2012 Befehlszeile verwenden, stellen Sie sicher, dass die %WinDir%\Microsoft.NET\Framework\v4.0.<current version> Verzeichnis befindet sich im Systempfad.If you do not use the Visual Studio 2012Visual Studio 2012 command prompt, make sure that the %WinDir%\Microsoft.NET\Framework\v4.0.<current version> directory is in the system path.

    Geben Sie an der Eingabeaufforderung services.msc ein, um auf den Dienststeuerungs-Manager (SCM) zuzugreifen.Type services.msc at the command prompt to access the Service Control Manager (SCM). Der Windows-Dienst müsste unter "Dienste" als "WCFWindowsServiceSample" angezeigt werden.The Windows service should appear in Services as "WCFWindowsServiceSample". Der WCF-Dienst kann nur auf Clients Antworten, wenn der Windows-Dienst ausgeführt wird.The WCF service can only respond to clients if the Windows service is running. Um den Dienst zu starten, klicken Sie darauf in der SCM, und wählen Sie "Start", oder geben Net start WCFWindowsServiceSample an der Eingabeaufforderung.To start the service, right-click it in the SCM and select "Start", or type net start WCFWindowsServiceSample at the command prompt.

  3. Wenn Sie Änderungen am Dienst vornehmen, müssen Sie ihn zuerst stoppen und dann deinstallieren.If you make changes to the service, you must first stop it and uninstall it. Beenden Sie den Dienst, mit der rechten Maustaste in des Diensts im dienststeuerungs-Manager aus, und wählen Sie "Beenden", oder Geben Sie net Stop WCFWindowsServiceSample an der Eingabeaufforderung.To stop the service, right-click the service in the SCM and select "Stop", or type net stop WCFWindowsServiceSample at the command prompt. Wenn Sie den Windows-Dienst beenden und anschließend einen Client ausführen, tritt eine Ausnahme vom Typ EndpointNotFoundException auf, wenn ein Client versucht, auf den Dienst zuzugreifen.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. So deinstallieren Sie Windows-Dienst des Typs Installutil/u bin\service.exe an der Eingabeaufforderung.To uninstall the Windows service type installutil /u bin\service.exe at the command prompt.

BeispielExample

In Folgenden finden Sie eine vollständige Liste des in diesem Thema verwendeten Codes: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
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

Wie bei der Option für das "Selbsthosting" muss auch bei der Hostumgebung des Windows-Diensts ein Teil des Hostcodes eine Komponente der Anwendung sein.Like the "Self-Hosting" option, the Windows service hosting environment requires that some hosting code be written as part of the application. Der Dienst wird als eine Konsolenanwendung implementiert und enthält seinen eigenen Hostingcode.The service is implemented as a console application and contains its own hosting code. In anderen Hostumgebungen, z. B. WAS (Windows Process Activation Service, Windows-Prozessaktivierungsdienst) in IIS (Internet Information Services, Internetinformationsdienste), müssen Entwickler keinen Hostcode schreiben.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.

Siehe auchSee Also

Vereinfachte KonfigurationSimplified Configuration
Hosten in einer verwalteten AnwendungHosting in a Managed Application
Hosting-DiensteHosting Services
Windows Server AppFabric-HostingfunktionenWindows Server App Fabric Hosting Features