WCFのちょっとした実験をしたいとか、ちょっとしたプロセス間通信をしたいといったときに、app.configだとかServiceReferenceだとかはわずらわしい。そんなときに使うコードサンプル。

WcfSampleServer.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace WcfSampleServer
{
    [System.ServiceModel.ServiceContract]
    public interface IHelloWorldService
    {
        [System.ServiceModel.OperationContract]
         void Hello();
    }

    public class HelloWorldService : IHelloWorldService
    {
        public void Hello()
        {
           System.Console.WriteLine("Hello, World");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            using (System.ServiceModel.ServiceHost host = new System.ServiceModel.ServiceHost(typeof(HelloWorldService)))
            {
                host.AddServiceEndpoint(typeof(IHelloWorldService),
                    new System.ServiceModel.NetNamedPipeBinding(),
                   "net.pipe://localhost/HelloWorld");
                host.Open();

                System.Console.WriteLine("Started host.");
                System.Console.ReadLine();

                host.Close();
            }
        }
    }

}
WCFSampleClient.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WcfSampleServer;

namespace WcfSampleClient
{
    class Program
    {
        static void Main(string[] args)
        {
            var channelFactory = new System.ServiceModel.ChannelFactory<IHelloWorldService>(
                    new System.ServiceModel.NetNamedPipeBinding(),
                    new System.ServiceModel.EndpointAddress("net.pipe://localhost/HelloWorld"));
            channelFactory.Open();
            IHelloWorldService proxy = channelFactory.CreateChannel();
            proxy.Hello();
            channelFactory.Close();
        }
    }
}