次の方法で共有


方法 : マネージ アプリケーションで WCF サービスをホストする

マネージ アプリケーションでサービスをホストするには、マネージ アプリケーション コード内にサービスのコードを埋め込み、サービスのエンドポイントをコードで強制的に定義するか、構成を使用して宣言により定義してから、または既定のエンドポイントを使用して、ServiceHost のインスタンスを作成します。

メッセージの受信を開始するには、ServiceHostOpen を呼び出します。これにより、サービスのリスナーが作成されて開きます。この方法によるサービスのホストは、マネージ アプリケーション自体がホスト作業を行うため、"自己ホスト" と呼ばれることがあります。サービスを閉じるには、ServiceHostSystem.ServiceModel.Channels.CommunicationObject.Close を呼び出します。

サービスは、マネージ Windows サービス、インターネット インフォメーション サービス (IIS)、または Windows プロセス アクティブ化サービス (WAS) でホストすることもできます。サービスのホスティング詳細情報、「ホスティング サービス」を参照してください。

マネージ アプリケーションでのサービスのホストは、展開するインフラストラクチャが最小限で済むため、最も柔軟性があります。マネージ アプリケーションでのホスティング サービス詳細情報、「マネージ アプリケーションのホスト」を参照してください。

次の手順では、自己ホスト型サービスをコンソール アプリケーションに実装する方法を示します。

自己ホスト型サービスを作成するには

  1. Visual Studio 2010 を開き、[ファイル] メニューの [新規作成][プロジェクト] の順にクリックします。

  2. [インストールされているテンプレート] ボックスで [Visual C#][Windows] または [Visual Basic][Windows] を選択します。Visual Studio 2010 の設定に応じて、選択した内容の 1 つまたは両方が [インストールされているテンプレート] ボックスの [他の言語] ノードに表示されます。

  3. [Windows] ボックスから [コンソール アプリケーション] を選択します。[名前] ボックスに「SelfHost」と入力して [OK] をクリックします。

  4. ソリューション エクスプローラー[SelfHost] を右クリックし、[参照の追加] をクリックします。[.NET] タブの [System.ServiceModel] をクリックし、[OK] をクリックします。

    ms731758.Tip(ja-jp,VS.100).gifヒント :
    ソリューション エクスプローラー ウィンドウが表示されない場合は、[表示] メニューの [ソリューション エクスプローラー] をクリックします。

  5. まだ開いていない場合は、ソリューション エクスプローラー[Program.cs] または [Module1.vb] をダブルクリックして、コード ウィンドウで開きます。ファイルの先頭に次のステートメントを追加します。

    Imports System.ServiceModel
    Imports System.ServiceModel.Description
    
    using System.ServiceModel;
    using System.ServiceModel.Description;
    
  6. サービス コントラクトを定義して実装します。この例では、サービスへの入力に基づいてメッセージを返す HelloWorldService を定義します。

    <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(ja-jp,VS.100).gif注 :
    サービス インターフェイスを定義および実装する方法詳細情報、「方法 : Windows Communication Foundation サービス コントラクトを定義する」および「方法 : Windows Communication Foundation サービス コントラクトを実装する」を参照してください。

  7. Main メソッドの上部で、サービスのベース アドレスで Uri クラスのインスタンスを作成します。

    Dim baseAddress As Uri = New Uri("https://localhost:8080/hello")
    
    Uri baseAddress = new Uri("https://localhost:8080/hello");
    
  8. ServiceHost クラスのインスタンスを作成して、サービス型を表す Type とベース アドレス URI (Uniform Resource Identifier) を ServiceHost に渡します。メタデータ公開を有効にして、ServiceHostOpen メソッドを呼び出し、サービスを初期化してメッセージを受信する準備をします。

    ' 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(ja-jp,VS.100).gif注 :
    この例では、既定のエンドポイントを使用するので、このサービスには構成ファイルは必要ありません。エンドポイントが構成されていない場合、ランタイムは、サービスによって実装されたサービス コントラクトごとに 1 つのエンドポイントを各ベース アドレスに作成します。既定のエンドポイントの詳細詳細情報、「簡略化された構成」および「WCF サービスの簡略化された構成」を参照してください。

  9. Ctrl キーと Shift キーを押しながら B キーを押して、ソリューションをビルドします。

サービスをテストするには

  1. Ctrl キーを押しながら F5 キーを押してサービスを実行します。

  2. [WCF のテスト用クライアント] を開きます。

    ms731758.Tip(ja-jp,VS.100).gifヒント :
    [WCF のテスト用クライアント] を開くには、Visual Studio 2010 コマンド プロンプトを開いて、WcfTestClient.exe を実行します。

  3. [ファイル] メニューの [サービスの追加] をクリックします。

  4. アドレス ボックスに「https://localhost:8080/hello」と入力し、[OK] をクリックします。

    ms731758.Tip(ja-jp,VS.100).gifヒント :
    サービスが実行していることを確認してください。サービスが実行していない場合、この手順は失敗します。コードでベース アドレスを変更した場合は、この手順で、変更したアドレスを使用します。

  5. [マイ サービス プロジェクト] ノードの [SayHello] をダブルクリックします。自分の名前を [要求] ボックスの [値] 列に入力して、[起動] をクリックします。応答メッセージが [応答] ボックスに表示されます。

HelloWorldService 型のサービスをホストする ServiceHost オブジェクトを作成し、ServiceHostOpen メソッドを呼び出す例を、次に示します。ベース アドレスがコードで指定され、メタデータ公開が有効化されていて、既定のエンドポイントが使用されています。

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

参照

処理手順

方法 : IIS で WCF サービスをホストする
自己ホスト
方法 : Windows Communication Foundation サービス コントラクトを定義する
方法 : Windows Communication Foundation サービス コントラクトを実装する

リファレンス

Uri
AppSettings
ConfigurationManager

概念

ホスティング サービス
ServiceModel メタデータ ユーティリティ ツール (Svcutil.exe)
サービスとクライアントを構成するためのバインディングの使用
システム標準のバインディング