Compartir a través de


Cómo implementar un contrato de servicio de Windows Communication Foundation

Ésta es la segunda de las seis tareas que son necesarias para crear un servicio Windows Communication Foundation (WCF) básico y un cliente que llame al servicio. Para obtener una introducción a las seis tareas, consulte el tema Tutorial de introducción.

La creación de un servicio WCF requiere que se cree primero el contrato, que se define mediante una interfaz. Para obtener más información sobre la creación de la interfaz, consulte Definición de un contrato de servicio de Windows Communication Foundation. El siguiente paso, mostrado en este ejemplo, es implementar la interfaz. Esto implica la creación de una clase denominada CalculatorService que implemente la interfaz ICalculator definida por el usuario. El código utilizado para esta tarea se proporciona en el ejemplo que sigue al procedimiento.

Para implementar un contrato de servicio WCF

  1. Cree una nueva clase denominada CalculatorService en el mismo archivo donde definió la interfaz ICalculator. CalculatorService implementa la interfaz ICalculator.

    Public Class CalculatorService
        Implements ICalculator
    
    public class CalculatorService : ICalculator
    
  2. Implemente cada método definido en la interfaz ICalculator dentro de la clase CalculatorService.

    Public Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Add
        Dim result As Double = n1 + n2
        ' Code added to write output to the console window.
        Console.WriteLine("Received Add({0},{1})", n1, n2)
        Console.WriteLine("Return: {0}", result)
        Return result
    End Function
    
    Public Function Subtract(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Subtract
        Dim result As Double = n1 - n2
        Console.WriteLine("Received Subtract({0},{1})", n1, n2)
        Console.WriteLine("Return: {0}", result)
        Return result
    
    End Function
    
    Public Function Multiply(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Multiply
        Dim result As Double = n1 * n2
        Console.WriteLine("Received Multiply({0},{1})", n1, n2)
        Console.WriteLine("Return: {0}", result)
        Return result
    
    End Function
    
    
    Public Function Divide(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Divide
        Dim result As Double = n1 / n2
        Console.WriteLine("Received Divide({0},{1})", n1, n2)
        Console.WriteLine("Return: {0}", result)
        Return result
    
    End Function
    
    public double Add(double n1, double n2)
    {
        double result = n1 + n2;
        Console.WriteLine("Received Add({0},{1})", n1, n2);
        // Code added to write output to the console window.
        Console.WriteLine("Return: {0}", result);
        return result;
    }
    
    public double Subtract(double n1, double n2)
    {
        double result = n1 - n2;
        Console.WriteLine("Received Subtract({0},{1})", n1, n2);
        Console.WriteLine("Return: {0}", result);
        return result;
    }
    
    public double Multiply(double n1, double n2)
    {
        double result = n1 * n2;
        Console.WriteLine("Received Multiply({0},{1})", n1, n2);
        Console.WriteLine("Return: {0}", result);
        return result;
    }
    
    public double Divide(double n1, double n2)
    {
        double result = n1 / n2;
        Console.WriteLine("Received Divide({0},{1})", n1, n2);
        Console.WriteLine("Return: {0}", result);
        return result;
    }
    
    ms734686.note(es-es,VS.100).gifNota:
    El código de salida de escritura se ha agregado para realizar las pruebas convenientes.

Ejemplo

El siguiente ejemplo de código muestra la interfaz que define el contrato de servicio y la implementación de la interfaz.

Imports System
Imports System.ServiceModel


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
    
    ' Step 1: Create service class that implements the service contract.
    Public Class CalculatorService
        Implements ICalculator
        
        ' Step 2: Implement functionality for the service operations.
        Public Function Add(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Add
            Dim result As Double = n1 + n2
            ' Code added to write output to the console window.
            Console.WriteLine("Received Add({0},{1})", n1, n2)
            Console.WriteLine("Return: {0}", result)
            Return result
        End Function

        Public Function Subtract(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Subtract
            Dim result As Double = n1 - n2
            Console.WriteLine("Received Subtract({0},{1})", n1, n2)
            Console.WriteLine("Return: {0}", result)
            Return result
        
        End Function

        Public Function Multiply(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Multiply
            Dim result As Double = n1 * n2
            Console.WriteLine("Received Multiply({0},{1})", n1, n2)
            Console.WriteLine("Return: {0}", result)
            Return result
        
        End Function
        
        
        Public Function Divide(ByVal n1 As Double, ByVal n2 As Double) As Double Implements ICalculator.Divide
            Dim result As Double = n1 / n2
            Console.WriteLine("Received Divide({0},{1})", n1, n2)
            Console.WriteLine("Return: {0}", result)
            Return result
        
        End Function
    End Class
End Namespace
using System;
using System.ServiceModel;

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);
    }

    // Step 1: Create service class that implements the service contract.
    public class CalculatorService : ICalculator
    {
         // Step 2: Implement functionality for the service operations.
        public double Add(double n1, double n2)
        {
            double result = n1 + n2;
            Console.WriteLine("Received Add({0},{1})", n1, n2);
            // Code added to write output to the console window.
            Console.WriteLine("Return: {0}", result);
            return result;
        }

        public double Subtract(double n1, double n2)
        {
            double result = n1 - n2;
            Console.WriteLine("Received Subtract({0},{1})", n1, n2);
            Console.WriteLine("Return: {0}", result);
            return result;
        }

        public double Multiply(double n1, double n2)
        {
            double result = n1 * n2;
            Console.WriteLine("Received Multiply({0},{1})", n1, n2);
            Console.WriteLine("Return: {0}", result);
            return result;
        }

        public double Divide(double n1, double n2)
        {
            double result = n1 / n2;
            Console.WriteLine("Received Divide({0},{1})", n1, n2);
            Console.WriteLine("Return: {0}", result);
            return result;
        }
    }
}

Ahora, el contrato de servicio se ha creado e implementado. Compile la solución para asegurarse de que no hay ningún error de compilación y, a continuación, continúe en Procedimiento para hospedar y ejecutar un servicio básico de Windows Communication Foundation para ejecutar el servicio. Para obtener más información para solucionar problemas, consulte Solución de problemas con el tutorial de introducción.

Compilar el código

Si está utilizando un compilador de línea de comandos, debe hacer referencia al ensamblado System.ServiceModel.

Si usa Visual Studio, en el menú Generar, haga clic en Generar solución (o presione CTRL+MAYÚS+B).

Vea también

Tareas

Ejemplo de introducción
Autohospedaje