まず、WCFとはMSDNの説明によると「 Windows Communication Foundation (WCF) は、サービス指向アプリケーションを構築するためのフレームワークです。 WCF を使用すると、1 つのサービス エンドポイントから別のサービス エンドポイントに非同期メッセージとしてデータを送信できます。 」ということです。
簡単に説明すると、サーバー/クライアント形式のアプリケーション通信を行うためのフレームワークになります。
WCFではTCPやHTTPを使用したサーバー/クライアント間の通信を行うことができる一方、同一マシン間で名前付きパイプを用いたプロセス間通信を行うことも可能です。
ここでは下記の3つの手順にしたがって簡単なプロセス間通信を実現してみます。
using System.ServiceModel; namespace WcfIpcSample { [ServiceContract] public interface IWcfIpcInterface { [OperationContract] string Hello(string name); } }
※プログラムで参照設定で「System.ServiceModel」を追加する必要があります。
using System; namespace WcfIpcSample { public class WcfIpcServer : IWcfIpcInterface { public string Hello(string name) { return string.Format("Hello {0}", name); } } }
1で作成したクラスライブラリを参照して、実際の処理を実装します。
using System; using System.ServiceModel; namespace WcfIpcSample { class Program { static void Main(string[] args) { string baseAddress = "net.pipe://localhost/WcfIpcSample"; string endPointAddress = "Ipc"; ServiceHost serviceHost = new ServiceHost(typeof(WcfIpcServer), new Uri(baseAddress)); serviceHost.AddServiceEndpoint(typeof(IWcfIpcInterface), new NetNamedPipeBinding(NetNamedPipeSecurityMode.None), endPointAddress); // WCFサービスの開始 serviceHost.Open(); // クライアントからの接続を待つ Console.ReadKey(); // WCFサービスの終了 serviceHost.Close(); } } }
2で実装したクラスを指定してServiceHostを起動してクライアントからの接続を待ちます。
using System; using System.ServiceModel; namespace WcfIpcSample { class Program { static void Main(string[] args) { using (ChannelFactory<IWcfIpcInterface> channelFactory = new ChannelFactory<IWcfIpcInterface>(new NetNamedPipeBinding(NetNamedPipeSecurityMode.None))) { string uri = @"net.pipe://localhost/WcfIpcSample/Ipc"; IWcfIpcInterface service = channelFactory.CreateChannel(new EndpointAddress(uri)); string result = service.Hello("Yamada"); Console.WriteLine(result); } } } }
3で実行しているWCFホストに接続します。今回の場合は「Hello Yamada!」が出力されます。