Aracılığıyla paylaş


Nasıl yapılır: Yönetilen uygulamada WCF hizmeti barındırma

Bir hizmeti yönetilen uygulama içinde barındırmak için, hizmetin kodunu yönetilen uygulama kodunun içine ekleyin, hizmet için kodda kesinlik temelli olarak, yapılandırma aracılığıyla bildirim temelli olarak veya varsayılan uç noktaları kullanarak bir uç nokta tanımlayın ve ardından örneğini ServiceHostoluşturun.

İletileri almaya başlamak için çağrısında Open bulunur ServiceHost. Bu, hizmetin dinleyicisini oluşturur ve açar. Yönetilen uygulama barındırma işinin kendisini yaptığı için bir hizmeti bu şekilde barındırmak genellikle "kendi kendine barındırma" olarak adlandırılır. Hizmeti kapatmak için çağrısında CommunicationObject.Close bulunur ServiceHost.

Bir hizmet yönetilen bir Windows hizmetinde, Internet Information Services'ta (IIS) veya Windows İşlem Etkinleştirme Hizmeti'nde (WAS) da barındırılabilir. Bir hizmetin barındırma seçenekleri hakkında daha fazla bilgi için bkz . Barındırma Hizmetleri.

Bir hizmeti yönetilen uygulamada barındırmak en esnek seçenektir çünkü dağıtılacak en az altyapıyı gerektirir. Yönetilen uygulamalarda hizmetleri barındırma hakkında daha fazla bilgi için bkz . Yönetilen Uygulamada Barındırma.

Aşağıdaki yordam, konsol uygulamasında şirket içinde barındırılan bir hizmetin nasıl uygulanduğunu gösterir.

Şirket içinde barındırılan hizmet oluşturma

  1. Yeni bir konsol uygulaması oluşturun:

    1. Visual Studio'yu açın ve Dosya menüsünden Yeni>Proje'yi seçin.

    2. Yüklü Şablonlar listesinde Visual C# veya Visual Basic'i ve ardından Windows Masaüstü'nü seçin.

    3. Konsol Uygulaması şablonunu seçin. Ad kutusuna yazın SelfHost ve Tamam'ı seçin.

  2. Çözüm Gezgini'da SelfHost'a sağ tıklayın ve Başvuru Ekle'yi seçin. .NET sekmesinden System.ServiceModel'ive ardından Tamam'ı seçin.

    İpucu

    Çözüm Gezgini penceresi görünmüyorsa Görünüm menüsünden Çözüm Gezginiseçin.

  3. Çözüm Gezgini'daki Program.cs veya Module1.vb çift tıklayarak açık değilse kod penceresinde açın. Dosyanın en üstüne aşağıdaki deyimleri ekleyin:

    using System.ServiceModel;
    using System.ServiceModel.Description;
    
    Imports System.ServiceModel
    Imports System.ServiceModel.Description
    
  4. Hizmet sözleşmesi tanımlama ve uygulama. Bu örnek, hizmet girişine göre bir ileti döndüren bir tanımlar HelloWorldService .

    [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
    

    Not

    Hizmet arabirimi tanımlama ve uygulama hakkında daha fazla bilgi için bkz . Nasıl yapılır: Hizmet Sözleşmesi Tanımlama ve Nasıl Yapılır: Hizmet Sözleşmesi Uygulama.

  5. yönteminin Main en üstünde, hizmetin temel adresiyle sınıfının bir örneğini Uri oluşturun.

    Uri baseAddress = new Uri("http://localhost:8080/hello");
    
    Dim baseAddress As Uri = New Uri("http://localhost:8080/hello")
    
  6. Hizmet türünü ve temel adresi Tekdüzen Kaynak Tanımlayıcısı'nı (URI) öğesine geçirerek Type sınıfının bir örneğini ServiceHostServiceHost(Type, Uri[])oluşturun. Meta veri yayımlamayı Open etkinleştirin ve hizmeti başlatmak ve iletileri almak üzere hazırlamak için üzerinde yöntemini ServiceHost çağırın.

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

    Not

    Bu örnekte varsayılan uç noktalar kullanılır ve bu hizmet için yapılandırma dosyası gerekmez. Hiçbir uç nokta yapılandırılmamışsa, çalışma zamanı hizmet tarafından uygulanan her hizmet sözleşmesi için her temel adres için bir uç nokta oluşturur. Varsayılan uç noktalar hakkında daha fazla bilgi için bkz. WCF Hizmetleri için Basitleştirilmiş Yapılandırma ve Basitleştirilmiş Yapılandırma.

  7. Çözümü oluşturmak için Ctrl+Shift B tuşlarına+basın.

Hizmeti test etme

  1. Hizmeti çalıştırmak için Ctrl+F5 tuşlarına basın.

  2. WCF Test İstemcisi'yi açın.

    İpucu

    WCF Test İstemcisi'ni açmak için Visual Studio için Geliştirici Komut İstemi'ni açın ve WcfTestClient.exe yürütür.

  3. Dosya menüsünden Hizmet Ekle'yi seçin.

  4. Adres kutusuna yazın http://localhost:8080/hello ve Tamam'a tıklayın.

    İpucu

    Hizmetin çalıştığından emin olun, aksi halde bu adım başarısız olur. Koddaki temel adresi değiştirdiyseniz, bu adımda değiştirilen temel adresi kullanın.

  5. Hizmet Projelerim düğümünü altındaki SayHello'ya çift tıklayın. İstek listesindeki Değer sütununa adınızı yazın ve Çağır'a tıklayın.

    Yanıt listesinde bir yanıt iletisi görüntülenir.

Örnek

Aşağıdaki örnek, türünde HelloWorldServicebir hizmeti barındırmak için bir ServiceHost nesnesi oluşturur ve yöntemini üzerinde ServiceHostçağırırOpen. Kodda bir temel adres sağlanır, meta veri yayımlama etkinleştirilir ve varsayılan uç noktalar kullanılır.

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

Ayrıca bkz.