Tuesday, May 13, 2008

Quick and Dirty WCF Service

Going to cover how to create and consume a WCF service.


Create


1. Create a new project, select "Web" project type and then choose "WCF Service Application".
2. Add a new WCF Service. This will add an interface and a .svc file with a code behind. 3. With the interface, define a method signature you want as your service.
using System.ServiceModel;

namespace MyService
{
    [ServiceContract]
    interface IWorkerService
    {
        [OperationContract]
        string DoWork(string workItem);
    }
}
This is called your "Contract".

4. Implement interface (contract) in the code behind of the .svc.
using System;

namespace MyService
{
    public class WorkerService : IWorkerService
    {
        public string DoWork(string workItem)
        {
            return string.Format("Work item: '{0}' received at: {1}", workItem, DateTime.Now);
        }
    }
}
That's it, your service is all set. Because you selected the web template, your service can be accessed via http by default.

Consume


1. Create a new Application, doesn't matter what kind.
2. Right-click on the References folder and select Add Service Reference...
3. In the Add Service Reference dialog, click the Discover button.
4. Your service should be discovered: 5. Accept the default Namespace and click OK.
6. Now you can instantiate and run this method:
ServiceReference1.WorkerServiceClient client = new ServiceReference1.WorkerServiceClient();
string result = client.DoWork("Some info.");
So you can see how this is much like creating a web service.

More Info: MSDN: Getting Started Tutorial (WCF)