Wednesday, June 9, 2010

Barebone WCF, the simplest, I believe. Look Ma, No XML!

ServiceStub.cs
using System.ServiceModel;

namespace TestServiceStub
{ 
 [ServiceContract]
 public interface ServiceStub
 {
  [OperationContract] 
  string GetData(string name);
 }
}

ServiceImpl.cs
using System;
using System.ServiceModel;

using TestServiceStub;

namespace TestServiceImpl
{ 
 public class ServiceImpl : ServiceStub
 { 
 
  public string GetData(string name)
  {
      return "Hello " + name;
  }  
  
  public static void Main()
  { 
   using ( var h = new ServiceHost(serviceType: typeof(ServiceImpl)) )
   {
       h.AddServiceEndpoint(

           implementedContract: typeof(ServiceStub), 

           binding: new NetTcpBinding(), 

           address: "net.tcp://localhost:777");
    
       h.Open();
    
       Console.WriteLine("Don't press any key");
       Console.ReadLine();
   }
  }
  
 }//class
}//namespace

Consume.cs
using System;
using System.ServiceModel;

using TestServiceStub;

namespace ServiceUser
{
 public class Program
 {
 
  public static void Main()
  {
    var factory = 
        new ChannelFactory<ServiceStub>(

            binding: new NetTcpBinding(), 

            remoteAddress: "net.tcp://localhost:777");
   
    ServiceStub service = factory.CreateChannel();
    Console.WriteLine("Test: {0}", service.GetData("Michael"));
    Console.ReadLine();
  }
  
 }//class 
}//namespace

To compile, run all these commands, put them in a batch file if you want to:
csc /target:library ServiceStub.cs
csc /reference:ServiceStub.dll ServiceImpl.cs
csc /reference:ServiceStub.dll Consume.cs

To launch the middle-tier:
C:\_CODE\_.NET\Test\wcf>start ServiceImpl.exe

To use the service(s) of middle-tier. Note: run this on separate command shell, leave the ServiceImpl.exe running
C:\_CODE\_.NET\Test\wcf>Consume.exe
Test: Hello Michael

No comments:

Post a Comment