WCF – Basics

I’ve used WCF (and the previous incarnation of web services in .NET) on and off for a while. However once the inital work to set the application up is completed I tend to forget much of what I’ve done to concentrate on the actual application. This is one of the great things with WCF – it just works once set-up.

So this post is going to be written as a quick refresher.

ABC

One of the key things to remember with WCF is the the setting up is pretty much all about the ABC’s

  • A is of Address. In other words what’s the location (or endpoint) of the service.
  • B is of Binding. How do we connect to the endpoint, i.e. what’s the protocol etc.
  • C is of Contract. The application/programming interface to the web service, i.e. what does it do ?

Contracts

Simply put, creating an interface and decorating the interface with [ServiceContract] will mark out an interface as a service contract. Marking the methods that you want to publish with [OperationContract] i.e.

[ServiceContract]
public interface IPlantService
{
   [OperationContract]
   List<Plant> GetPlants();
   // and so on
}

where we’re passing our own complex types back (in the above we have the Plant class) here we mark the class with [DataContract] attribute and each property we wish to publish are marked with [DataMember] as per

[DataContract]
public class Plant
{
   [DataMember]
   public int Id { get; set; }
   [DataMember]
   public string CommonName { get; set; }
   // ... and so on
}

Don’t forget to include the System.ServiceModel assembly and System.Runtime.Serialization.

Hosting a service outside of IIS

Whilst IIS offers a scaleable, consistent and secure architecture for hosting WCF web services, one might prefer to host via a console app or Windows service for example. The following is a simple example of the code needed to get WCF self hosted in a console application.

class Program
{
   static void Main(string[] args)
   {
      ServiceHost serviceHost = new ServiceHost(typeof(PlantService));
      serviceHost.Open();
      Console.WriteLine("Service Running");
      Console.ReadLine();
      serviceHost.Close();
   }
}

Configuring the ABC’s

Configuration of the ABC’s can be accomplished through code or more usually through configuration. I’m not going to dig deep into configuration but instead point to something I’ve only recently been made aware of. Having always edited the app.config by hand.

It’s slightly strange in Visual Studio 2010 how you enable this option but go to Tools | WCF Service Configuration Editor then close it. Now if you right mouse click to get the context menu on the App.config file you’ll see the Edit WCF Configuration option. Now you can configure WCF via this UI.