Compartir a través de


Hospedaje de un servicio WCF en una aplicación administrada

Para hospedar un servicio dentro de una aplicación administrada, incruste el código del servicio dentro del código de la aplicación administrada, defina un extremo para el servicio de manera imperativa mediante código, de manera declarativa mediante configuración o usando extremos predeterminados y, a continuación, cree una instancia de ServiceHost.

Para comenzar a recibir mensajes, llame al método Open en ServiceHost. Esto crea y abre el agente de escucha del servicio. Hospedar un servicio de esta manera se conoce a menudo como "autohospedaje", puesto que la aplicación administrada está haciendo el propio trabajo de hospedaje. Para cerrar el servicio, llame al método System.ServiceModel.Channels.CommunicationObject.Close en ServiceHost.

Un servicio también se puede hospedar en un servicio de Windows administrado, en Internet Information Services (IIS), o en Windows Process Activation Service (WAS). Para obtener más información sobre las opciones de hospedaje de un servicio, vea Servicios de hospedaje.

Hospedar un servicio en una aplicación administrada es la opción más flexible puesto que es la opción que menos infraestructura requiere que se implemente. Para obtener más información sobre el hospedaje de servicios en aplicaciones administradas, vea Hospedaje en una aplicación administrada.

El siguiente procedimiento muestra cómo implementar un servicio autohospedado en una aplicación de consola.

Creación de un servicio autohospedado

  1. Abra Visual Studio 2010 y seleccione Nuevo, Proyecto en el menú Archivo.

  2. En la lista Plantillas instaladas, seleccione Visual C#, Windows o Visual Basic, Windows. Dependiendo de la configuración de Visual Studio 2010, uno o ambas de estas opciones pueden estar debajo del nodo Otros lenguajes de la lista Plantillas instaladas.

  3. Seleccione Aplicación de consola en la lista Windows. Escriba SelfHost en el cuadro Nombre y haga clic en Aceptar.

  4. Haga clic con el botón secundario en SelfHost en el Explorador de soluciones y seleccione Agregar referencia. Seleccione System.ServiceModel en la pestaña .NET y haga clic en Aceptar.

    ms731758.Tip(es-es,VS.100).gifSugerencia:
    Si la ventana Explorador de soluciones no está visible, seleccione Explorador de soluciones en el menú Ver.

  5. Haga doble clic en Program.cs o Module1.vb en el Explorador de soluciones para abrirlo en la ventana de código si aún no lo está. Agregue las instrucciones siguientes en la parte superior del archivo.

    Imports System.ServiceModel
    Imports System.ServiceModel.Description
    
    using System.ServiceModel;
    using System.ServiceModel.Description;
    
  6. Defina e implemente un contrato de servicio. En este ejemplo se define un HelloWorldService que devuelve un mensaje en función de la entrada al servicio.

    <ServiceContract()>
    Public Interface IHelloWorldService
        <OperationContract()>
        Function SayHello(ByVal name As String) As String
    End Interface
    
    Public Class HelloWorldService
        Implements IHelloWorldService
    
        Public Function SayHello(ByVal name As String) As String Implements IHelloWorldService.SayHello
            Return String.Format("Hello, {0}", name)
        End Function
    End Class
    
    [ServiceContract]
    public interface IHelloWorldService
    {
        [OperationContract]
        string SayHello(string name);
    }
    
    public class HelloWorldService : IHelloWorldService
    {
        public string SayHello(string name)
        {
            return string.Format("Hello, {0}", name);
        }
    }
    
    ms731758.note(es-es,VS.100).gifNota:
    Para obtener más información sobre cómo definir e implementar una interfaz de servicio, vea Definición de un contrato de servicio de Windows Communication Foundation y Cómo implementar un contrato de servicio de Windows Communication Foundation.

  7. Al principio del método Main, cree una instancia de la clase Uri con la dirección base del servicio.

    Dim baseAddress As Uri = New Uri("https://localhost:8080/hello")
    
    Uri baseAddress = new Uri("https://localhost:8080/hello");
    
  8. Cree una instancia de la clase ServiceHost, pasando un Type que representa el tipo de servicio y el Identificador uniforme de recursos (URI) de la dirección base al ServiceHost. Habilite la publicación de metadatos y, a continuación, llame al método Open en ServiceHost para inicializar el servicio y prepararlo para recibir mensajes.

    ' Create the ServiceHost.
    Using host As New ServiceHost(GetType(HelloWorldService), baseAddress)
    
        ' Enable metadata publishing.
        Dim smb As New ServiceMetadataBehavior()
        smb.HttpGetEnabled = True
        smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15
        host.Description.Behaviors.Add(smb)
    
        ' Open the ServiceHost to start listening for messages. Since
        ' no endpoints are explicitly configured, the runtime will create
        ' one endpoint per base address for each service contract implemented
        ' by the service.
        host.Open()
    
        Console.WriteLine("The service is ready at {0}", baseAddress)
        Console.WriteLine("Press <Enter> to stop the service.")
        Console.ReadLine()
    
        ' Close the ServiceHost.
        host.Close()
    
    End Using
    
    // Create the ServiceHost.
    using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
    {
        // Enable metadata publishing.
        ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
        smb.HttpGetEnabled = true;
        smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
        host.Description.Behaviors.Add(smb);
    
        // Open the ServiceHost to start listening for messages. Since
        // no endpoints are explicitly configured, the runtime will create
        // one endpoint per base address for each service contract implemented
        // by the service.
        host.Open();
    
        Console.WriteLine("The service is ready at {0}", baseAddress);
        Console.WriteLine("Press <Enter> to stop the service.");
        Console.ReadLine();
    
        // Close the ServiceHost.
        host.Close();
    }
    
    ms731758.note(es-es,VS.100).gifNota:
    En este ejemplo se usan extremos predeterminados, y este servicio no requiere ningún archivo de configuración. Si no se configura ningún extremo, el motor en tiempo de ejecución crea uno para cada dirección base de cada contrato de servicio implementado por el servicio. Para obtener más información sobre los extremos predeterminados, vea Configuración simplificada y Configuración simplificada de los servicios de WCF.

  9. Presione Ctrl+MAYÚS+B para compilar la solución.

Para probar el servicio

  1. Presione Ctrl + F5 para ejecutar el servicio.

  2. Abra el Cliente de prueba WCF.

    ms731758.Tip(es-es,VS.100).gifSugerencia:
    Para abrir el Cliente de prueba WCF, abra un símbolo del sistema de Visual Studio 2010 y ejecute WcfTestClient.exe.

  3. Seleccione Agregar servicio... en el menú Archivo.

  4. Escriba https://localhost:8080/hello en el cuadro de dirección y haga clic en Aceptar.

    ms731758.Tip(es-es,VS.100).gifSugerencia:
    Asegúrese de que el servicio se está ejecutando; de lo contrario, este paso producirá un error. Si ha cambiado la dirección base en el código, use dicha dirección en este paso.

  5. Haga doble clic en SayHello debajo del nodo Mis proyectos de servicios. Escriba su nombre en la columna Valor de la lista Solicitud y haga clic en Invocar. Aparecerá un mensaje de respuesta en la lista Respuesta.

Ejemplo

El siguiente ejemplo crea un objeto ServiceHost para hospedar un servicio de tipo HelloWorldService, y, a continuación, llama al método Open en ServiceHost. Se proporciona una dirección base mediante código, se habilita la publicación de metadatos y se usan extremos predeterminados.

Imports System.ServiceModel
Imports System.ServiceModel.Description

Module Module1

    <ServiceContract()>
    Public Interface IHelloWorldService
        <OperationContract()>
        Function SayHello(ByVal name As String) As String
    End Interface
    
    Public Class HelloWorldService
        Implements IHelloWorldService

        Public Function SayHello(ByVal name As String) As String Implements IHelloWorldService.SayHello
            Return String.Format("Hello, {0}", name)
        End Function
    End Class

    Sub Main()
        Dim baseAddress As Uri = New Uri("https://localhost:8080/hello")

        ' Create the ServiceHost.
        Using host As New ServiceHost(GetType(HelloWorldService), baseAddress)

            ' Enable metadata publishing.
            Dim smb As New ServiceMetadataBehavior()
            smb.HttpGetEnabled = True
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15
            host.Description.Behaviors.Add(smb)

            ' Open the ServiceHost to start listening for messages. Since
            ' no endpoints are explicitly configured, the runtime will create
            ' one endpoint per base address for each service contract implemented
            ' by the service.
            host.Open()

            Console.WriteLine("The service is ready at {0}", baseAddress)
            Console.WriteLine("Press <Enter> to stop the service.")
            Console.ReadLine()

            ' Close the ServiceHost.
            host.Close()

        End Using

    End Sub

End Module
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;

namespace SelfHost
{
    [ServiceContract]
    public interface IHelloWorldService
    {
        [OperationContract]
        string SayHello(string name);
    }

    public class HelloWorldService : IHelloWorldService
    {
        public string SayHello(string name)
        {
            return string.Format("Hello, {0}", name);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("https://localhost:8080/hello");

            // Create the ServiceHost.
            using (ServiceHost host = new ServiceHost(typeof(HelloWorldService), baseAddress))
            {
                // Enable metadata publishing.
                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
                host.Description.Behaviors.Add(smb);

                // Open the ServiceHost to start listening for messages. Since
                // no endpoints are explicitly configured, the runtime will create
                // one endpoint per base address for each service contract implemented
                // by the service.
                host.Open();

                Console.WriteLine("The service is ready at {0}", baseAddress);
                Console.WriteLine("Press <Enter> to stop the service.");
                Console.ReadLine();

                // Close the ServiceHost.
                host.Close();
            }
        }
    }
}

Vea también

Tareas

Procedimiento para hospedar un servicio WCF en IIS
Autohospedaje
Definición de un contrato de servicio de Windows Communication Foundation
Cómo implementar un contrato de servicio de Windows Communication Foundation

Referencia

Uri
AppSettings
ConfigurationManager

Conceptos

Servicios de hospedaje
Herramienta de utilidad de metadatos de ServiceModel (Svcutil.exe)
Utilización de enlaces para configurar servicios y clientes
Enlaces proporcionados por el sistema