いろいろ備忘録日記

主に .NET とか Go とか Flutter とか Python絡みのメモを公開しています。

WCF入門-002 (簡単なサンプル, アプリケーション構成ファイルに記述)


前回のサンプルを、アプリケーション構成ファイルを利用するようにした版。


アプリケーション構成ファイルに設定を記述することで
コードからエンドポイントの記述が無くなる。
通常は、アプリケーション構成ファイルに設定を記述する。


以下、アプリケーション構成ファイル。service要素の内容が大事。
mexエンドポイントの設定は、サービス参照を行う際に必要。

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyServiceBehavior">
          <serviceMetadata httpGetEnabled="True" />
          <serviceDebug includeExceptionDetailInFaults="True" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <services>
      <service name="MyService.MyService" behaviorConfiguration="MyServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8081/WCFSample002"/>
          </baseAddresses>
        </host>
        <endpoint address="SayHello" binding="basicHttpBinding" contract="MyService.IMyService" />
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
  </system.serviceModel>
</configuration>


以下、サービスインターフェースとサービスクラス。

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;

namespace MyService
{
    [ServiceContract(Namespace="http://Gsf.Samples.WCF/")]
    public interface IMyService
    {
        [OperationContract]
        string SayHello(string name);
    }
}


using System;
using System.Collections.Generic;
using System.Linq;

namespace MyService
{
    public class MyService : IMyService
    {
        public string SayHello(string name)
        {
            Console.WriteLine("[CALL] MyService.SayHello()");
            return string.Format("Hello. '{0}'!", name);
        }
    }
}


ホストクラス。前回は、ServiceHostを構築する際にエンドポイントの設定を行っていたが
今回はアプリケーション構成ファイルにて設定しているので必要ない。

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;

namespace Gsf.Samples.WCF
{
    class Program
    {
        static void Main()
        {
            //
            // サービスホストを構築する.
            //   エンドポイントアドレスなどの設定は、アプリケーション構成ファイルから読み込まれる。
            //
            using (ServiceHost host = new ServiceHost(typeof(MyService.MyService)))
            {
                host.Open();

                Console.WriteLine("サービスを開始しました。");
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();

                host.Close();
            }
        }
    }
}


クライアント側は「サービス参照の追加」を利用して
クライアントプロキシを自動生成して実行。


あらかじめホストアプリを実行しておき
VisualStudio上から、「サービス参照の追加」を実行すること。


(追記)
あとから「サービス参照の追加」の画面を見てみたら、「探索」ボタン
を押下すると、いちいちホストアプリを別で起動していなくてもサービス参照を追加できるみたい。
ただし、この場合はサービスが存在するプロジェクトを「WCFサービスライブラリ」プロジェクト
として作成していないといけない。

自動生成されたクラスを利用することで、クライアント側でも
エンドポイントの指定などが必要なくなる。便利〜。

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Windows.Forms;

using Gsf.Samples.WCF.MyServiceReference;

namespace Gsf.Samples.WCF
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            lblResult.Text = string.Empty;
            ActiveControl = btnCallSerivceMethod;
        }

        private void btnCallSerivceMethod_Click(object sender, EventArgs e)
        {
            string result = string.Empty;
            try
            {
                //
                // 「サービス参照の追加」によって、作成されたクライアントを利用して
                // サービスメソッドの呼び出しを行う.
                //
                using (MyServiceClient client = new MyServiceClient())
                {
                    client.Open();
                    result = client.SayHello("WCF Study");
                    client.Close();
                }
            }
            catch (CommunicationException ex)
            {
                MessageBox.Show(ex.Message);
            }

            lblResult.Text = result;
        }
    }
}


実行すると以下のようになります。


サンプルは以下の場所にアップしてあります。
https://sites.google.com/site/gsfzero1/Home/WCF-Sample-002.zip?attredirects=0&d=1



================================
過去の記事については、以下のページからご参照下さい。