Udostępnij za pośrednictwem


Instrukcje: hostowanie usługi WCF w aplikacji zarządzanej

Aby hostować usługę wewnątrz aplikacji zarządzanej, osadź kod usługi wewnątrz kodu aplikacji zarządzanej, zdefiniuj punkt końcowy usługi w kodzie, deklaratywnie za pomocą konfiguracji lub przy użyciu domyślnych punktów końcowych, a następnie utwórz wystąpienie klasy ServiceHost.

Aby rozpocząć odbieranie komunikatów, wywołaj polecenie Open .ServiceHost Spowoduje to utworzenie i otwarcie odbiornika dla usługi. Hostowanie usługi w ten sposób jest często określane jako "self-hosting", ponieważ zarządzana aplikacja wykonuje samą pracę hostingową. Aby zamknąć usługę, wywołaj polecenie CommunicationObject.Close .ServiceHost

Usługę można również hostować w zarządzanej usłudze systemu Windows, w usługach Internet Information Services (IIS) lub w usłudze aktywacji procesów systemu Windows (WAS). Aby uzyskać więcej informacji na temat opcji hostingu dla usługi, zobacz Hosting Services.

Hostowanie usługi w aplikacji zarządzanej jest najbardziej elastyczną opcją, ponieważ wymaga najmniejszej infrastruktury do wdrożenia. Aby uzyskać więcej informacji na temat hostowania usług w aplikacjach zarządzanych, zobacz Hosting w aplikacji zarządzanej.

Poniższa procedura przedstawia sposób implementowania samoobsługowej usługi w aplikacji konsolowej.

Tworzenie samoobsługowej usługi

  1. Utwórz nową aplikację konsolową:

    1. Otwórz program Visual Studio i wybierz pozycję Nowy>projekt z menu Plik.

    2. Na liście Zainstalowane szablony wybierz pozycję Visual C# lub Visual Basic, a następnie wybierz pozycję Windows Desktop.

    3. Wybierz szablon Aplikacja konsolowa. Wpisz SelfHost w polu Nazwa, a następnie wybierz przycisk OK.

  2. Kliknij prawym przyciskiem myszy pozycję SelfHost w Eksplorator rozwiązań i wybierz polecenie Dodaj odwołanie. Wybierz pozycję System.ServiceModel na karcie .NET , a następnie wybierz przycisk OK.

    Napiwek

    Jeśli okno Eksplorator rozwiązań nie jest widoczne, wybierz pozycję Eksplorator rozwiązań z menu Widok.

  3. Kliknij dwukrotnie Program.cs lub Module1.vb w Eksplorator rozwiązań, aby otworzyć go w oknie kodu, jeśli nie jest jeszcze otwarty. Dodaj następujące instrukcje w górnej części pliku:

    using System.ServiceModel;
    using System.ServiceModel.Description;
    
    Imports System.ServiceModel
    Imports System.ServiceModel.Description
    
  4. Definiowanie i implementowanie kontraktu usługi. W tym przykładzie zdefiniowano HelloWorldService komunikat, który zwraca komunikat na podstawie danych wejściowych usługi.

    [ServiceContract]
    public interface IHelloWorldService
    {
        [OperationContract]
        string SayHello(string name);
    }
    
    public class HelloWorldService : IHelloWorldService
    {
        public string SayHello(string name)
        {
            return string.Format("Hello, {0}", name);
        }
    }
    
    <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
    

    Uwaga

    Aby uzyskać więcej informacji na temat definiowania i implementowania interfejsu usługi, zobacz How to: Define a Service Contract (Jak zdefiniować kontrakt usługi) i How to: Implement a Service Contract (Instrukcje: implementowanie kontraktu usługi).

  5. W górnej części Main metody utwórz wystąpienie Uri klasy z adresem podstawowym usługi.

    Uri baseAddress = new Uri("http://localhost:8080/hello");
    
    Dim baseAddress As Uri = New Uri("http://localhost:8080/hello")
    
  6. Utwórz wystąpienie ServiceHost klasy, przekazując element Type reprezentujący typ usługi i podstawowy adres Uniform Resource Identifier (URI) do klasy ServiceHost(Type, Uri[]). Włącz publikowanie metadanych, a następnie wywołaj metodę Open w obiekcie ServiceHost , aby zainicjować usługę i przygotować ją do odbierania komunikatów.

    // 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();
    }
    
    ' 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
    

    Uwaga

    W tym przykładzie użyto domyślnych punktów końcowych, a dla tej usługi nie jest wymagany żaden plik konfiguracji. Jeśli nie skonfigurowano żadnych punktów końcowych, środowisko uruchomieniowe tworzy jeden punkt końcowy dla każdego adresu podstawowego dla każdego kontraktu usługi zaimplementowanego przez usługę. Aby uzyskać więcej informacji na temat domyślnych punktów końcowych, zobacz Uproszczona konfiguracja i Uproszczona konfiguracja dla usług WCF.

  7. Naciśnij klawisze Ctrl+Shift+B, aby skompilować rozwiązanie.

Testowanie usługi

  1. Naciśnij klawisze Ctrl+F5, aby uruchomić usługę.

  2. Otwórz klienta testowego programu WCF.

    Napiwek

    Aby otworzyć klienta testowego programu WCF, otwórz wiersz polecenia dewelopera dla programu Visual Studio i wykonaj WcfTestClient.exe.

  3. Wybierz pozycję Dodaj usługę z menu Plik .

  4. Wpisz http://localhost:8080/hello w polu adresu i kliknij przycisk OK.

    Napiwek

    Upewnij się, że usługa jest uruchomiona lub ten krok kończy się niepowodzeniem. Jeśli w kodzie zmieniono adres podstawowy, użyj zmodyfikowanego adresu podstawowego w tym kroku.

  5. Kliknij dwukrotnie pozycję SayHello w węźle Moje projekty usług. Wpisz swoją nazwę w kolumnie Value (Wartość) na liście Request (Żądanie), a następnie kliknij przycisk Invoke (Wywołaj).

    Na liście Odpowiedzi zostanie wyświetlony komunikat odpowiedzi .

Przykład

Poniższy przykład tworzy ServiceHost obiekt do hostowania usługi typu HelloWorldService, a następnie wywołuje metodę w metodzie Open .ServiceHost Adres podstawowy jest udostępniany w kodzie, funkcja publikowania metadanych jest włączona, a domyślne punkty końcowe są używane.

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("http://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();
            }
        }
    }
}
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("http://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

Zobacz też