構成ファイルを全く書かずに WCF を使ってみた

構成ファイルを全く書かずに WCF を使ってみました。

まずサービスコントラクトを定義。今回は単純なインタフェースにしておきます。

[ServiceContract]
public interface IMyService
{
    [OperationContract]
    string Hello(string name);
}

次にサービスを実装。

public class MyService : IMyService
{
    public string Hello(string name)
    {
        return "Hello " + name;
    }
}

ホストはコンソールアプリケーションとして作成します。エンドポイントは構成ファイルに記述せず、直接コードで指定します。

class Program
{
    static void Main(string[] args)
    {
        // TCP 利用
        Binding binding = new NetTcpBinding();

        // アドレス作成
        string protocol="net.tcp";
        string port="8080";
        string address = string.Format(
            "{0}://{1}:{2}/MyService", protocol, "localhost", port);

        // ホスト作成
        ServiceHost host = new ServiceHost(typeof(MyService.MyService));
	
        // エンドポイント追加
        host.AddServiceEndpoint(typeof(IMyService), binding, address);

        // サービス開始
        host.Open();

        Console.WriteLine("サービスを開始しました。終了するには Enter キーを押してください。");
        Console.ReadLine();

        // サービス終了
        host.Close();
    }
}

最後にクライアント。クライアントもコンソールアプリケーションで作成します。構成ファイルを使わないので、もちろんエンドポイントも直接コードで指定します。

class Program
{
    static void Main(string[] args)
    {
        ChannelFactory<IMyService> factory = new ChannelFactory<IMyService>();

        // バインディングは TCP
        factory.Endpoint.Binding = new NetTcpBinding();

        // アドレスを設定
        string protocol = "net.tcp";
        string port = "8080";
        string address = string.Format(
            "{0}://{1}:{2}/MyService", protocol, "localhost", port);
        factory.Endpoint.Address = new EndpointAddress(address);

        // コントラクトを設定
        factory.Endpoint.Contract.ContractType = typeof(IMyService);

        // チャネル作成
        IMyService channel = factory.CreateChannel();

        // サービス呼び出し
        string reply = channel.Hello("Wankuma");

        // 閉じる
        ((IChannel)channel).Close();

        // 戻り値を表示
        Console.WriteLine(reply);

        Console.ReadLine();
    }
}

まあ、このような使い方をする場面は少ないと思いますし、エンドポイントは構成ファイルに記述すべきです。

それにしても、WCF の書籍は全然ないですね。洋書だといくつかありますが、日本語の本は皆無です。WF ですらあるのに…。