Cara: Meng-hosting layanan WCF di aplikasi terkelola

Untuk meng-hosting layanan di dalam aplikasi terkelola, sematkan kode untuk layanan di dalam kode aplikasi terkelola, tentukan titik akhir untuk layanan baik secara imperatif dalam kode maupun secara deklaratif melalui konfigurasi, atau menggunakan titik akhir default, lalu buat instans ServiceHost.

Untuk mulai menerima pesan, panggil Open di ServiceHost. Panggilan ini membuat dan membuka pendengar untuk layanan. Hosting layanan dengan cara ini sering disebut sebagai "hosting mandiri" karena aplikasi terkelola melakukan pekerjaan hosting itu sendiri. Untuk menutup layanan, panggil CommunicationObject.Close di ServiceHost.

Layanan juga dapat di-hosting di layanan Windows terkelola, di Layanan Informasi Internet (IIS), atau di Windows Process Activation Service (WAS). Untuk informasi selengkapnya tentang opsi hosting untuk layanan, lihat Layanan Hosting.

Hosting layanan dalam aplikasi terkelola adalah opsi yang paling fleksibel karena membutuhkan infrastruktur paling sedikit untuk disebarkan. Untuk informasi selengkapnya tentang hosting layanan dalam aplikasi terkelola, lihat Hosting di Aplikasi Terkelola.

Prosedur berikut menunjukkan cara menerapkan layanan yang di-host sendiri di aplikasi konsol.

Membuat layanan yang di-hosting sendiri

  1. Membuat aplikasi konsol baru:

    1. Buka Visual Studio dan pilih Proyek>Baru dari menu File.

    2. Di daftar Templat Terpasang, pilih Visual C# atau Visual Basic, lalu pilih Windows Desktop.

    3. Pilih templat Aplikasi Konsol. Ketik SelfHost dalam kotak Nama lalu pilih OK.

  2. Klik kanan SelfHost di Penjelajah Solusi dan pilih Tambahkan Referensi. Pilih System.ServiceModel dari tab .NET lalu pilih OK.

    Tip

    Jika jendela Penjelajah Solusi tidak terlihat, pilih Penjelajah Solusi dari menu Tampilan.

  3. Klik dua kali Program.cs atau Module1.vb di Penjelajah Solusi untuk membukanya di jendela kode, jika belum terbuka. Tambahkan pernyataan berikut ke bagian atas file:

    using System.ServiceModel;
    using System.ServiceModel.Description;
    
    Imports System.ServiceModel
    Imports System.ServiceModel.Description
    
  4. Tentukan dan terapkan kontrak layanan. Contoh ini mendefinisikan HelloWorldService yang mengembalikan pesan berdasarkan input ke layanan.

    [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
    

    Catatan

    Untuk informasi selengkapnya tentang cara menentukan dan menerapkan antarmuka layanan, lihat Cara: Menentukan Kontrak Layanan dan Cara: Menerapkan Kontrak Layanan.

  5. Di bagian atas metode Main, buat instans kelas Uri dengan alamat dasar untuk layanan.

    Uri baseAddress = new Uri("http://localhost:8080/hello");
    
    Dim baseAddress As Uri = New Uri("http://localhost:8080/hello")
    
  6. Buat instans kelas ServiceHost, meneruskan Type yang mewakili jenis layanan dan alamat dasar Pengidentifikasi Sumber Daya Seragam (URI) ke ServiceHost(Type, Uri[]). Aktifkan penerbitan metadata, lalu panggil metode Open pada ServiceHost untuk menginisialisasi layanan dan menyiapkannya untuk menerima pesan.

    // 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
    

    Catatan

    Contoh ini menggunakan titik akhir default, dan tidak ada file konfigurasi yang diperlukan untuk layanan ini. Jika tidak ada titik akhir yang dikonfigurasi, maka runtime bahasa umum membuat satu titik akhir untuk setiap alamat dasar untuk setiap kontrak layanan yang diterapkan oleh layanan. Untuk informasi selengkapnya tentang titik akhir default, lihat Konfigurasi Sederhana dan Konfigurasi Sederhana untuk Layanan WCF.

  7. Tekan Ctrl+Shift+B untuk membuat aplikasi.

Menguji layanan

  1. Tekan Ctrl+F5 untuk menjalankan layanan.

  2. Buka Klien Pengujian WCF.

    Tip

    Untuk membuka Klien Pengujian WCF, buka Perintah Pengembang untuk Visual Studio dan jalankan WcfTestClient.exe.

  3. Pilih Tambahkan Layanan dari menu File.

  4. Ketik http://localhost:8080/hello ke dalam kotak alamat dan klik OK.

    Tip

    Pastikan layanan berjalan atau langkah ini gagal. Jika Anda telah mengubah alamat dasar dalam kode, gunakan alamat dasar yang dimodifikasi dalam langkah ini.

  5. Klik dua kali SayHello di bawah node Proyek Layanan Saya. Ketik nama Anda ke dalam kolom Nilai di daftar Permintaan, dan klik Panggil.

    Pesan balasan muncul di daftar Respons.

Contoh

Contoh berikut membuat objek ServiceHost untuk meng-hosting layanan jenis HelloWorldService, lalu memanggil metode Open pada ServiceHost. Alamat dasar disediakan dalam kode, penerbitan metadata diaktifkan, dan titik akhir default digunakan.

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

Lihat juga