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 w kodzie 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 ServiceHost.

Aby rozpocząć odbieranie komunikatów, wywołaj Open w ServiceHost. Powoduje to utworzenie i otwarcie nasłuchiwacza 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 CommunicationObject.Close w 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 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>project z menu pliku.

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

    3. Wybierz szablon aplikacji konsolowej. Wpisz SelfHost w polu Nazwa, a następnie wybierz OK.

  2. Kliknij prawym przyciskiem myszy SelfHost w eksploratorze rozwiązań i wybierz pozycję Dodaj odwołanie. Wybierz System.ServiceModel z karty .NET, a następnie kliknij OK.

    Wskazówka

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

  3. Kliknij dwukrotnie Program.cs lub Module1.vb w Eksploratorze 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, 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 and How to: Implement a Service Contract.

  5. W górnej części metody Main utwórz wystąpienie klasy Uri przy użyciu adresu podstawowego dla 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 klasy ServiceHost, przekazując Type, który reprezentuje typ usługi, oraz identyfikator URI (Uniform Resource Identifier) adresu podstawowego do ServiceHost(Type, Uri[]). Włącz publikowanie metadanych, a następnie wywołaj metodę Open na 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 {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 Ctrl+Shift+B, aby skompilować rozwiązanie.

Testowanie usługi

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

  2. Otwórz klienta testowego programu WCF.

    Wskazówka

    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.

    Wskazówka

    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 SayHello w węźle Moje projekty usług. Wpisz swoją nazwę w kolumnie Wartość na liście Żądanie, a następnie kliknij Wywołaj.

    Komunikat odpowiedzi pojawia się na liście odpowiedzi.

Przykład

Poniższy przykład tworzy obiekt ServiceHost do hostowania usługi typu HelloWorldService, a następnie wywołuje metodę Open w 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 {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ż