Introduction
WCF (Windows Communication Foundation) is a great framework for developing service oriented applications. This article explains the steps needed to use a WCF service from a client application.
Background
The best starter guide for WCF I could find was this. It guides you step-by-step to create a WCF service and a client application. However, the steps needed to create the client application and call the methods exposed by the service did not sound so handy. The article says that before the client application can use the service, we should run svcutil.exe to generate the proxy classes. These proxy classes are then used to access the methods exposed by the service.
There must be a better option. This article explains how to add a Web Reference to a WCF service in a client application.
Using the code
Create a WCF service as per the steps explained in the Hello World sample. If you do not want to create the service from scratch, you can download the WCF Service Source.zip attached with this article.
Once you have the service ready, compile and run it. You will see the console window open up. At this stage, the service is ready, and client applications can call methods exposed by the service.
Most of you who have worked with .NET web services would certainly agree with me that Web References are the easiest way to invoke a web service. I was trying to do the same with the WCF service. However, I saw that the Service Discovery Operation failed to recognize the service because Metadata Publishing is not enabled.
The following configuration settings show how to enable Metadata Publishing on a WCF service:
="1.0"="utf-8"
<configuration>
<system.serviceModel>
<services>
<service name="HelloService.HelloService"
behaviorConfiguration="HelloService.HelloService" />
</services>
<behaviors>
<serviceBehaviors>
<behavior name="HelloService.HelloService" >
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
The above configuration settings will enable Metadata Publishing on the service.
Now, let us create a client application which accesses the HelloService. Either create an application from scratch, or you could use the WCF Client Source.zip attached with this article.
Follow the steps below to create a client application:
- Create a VB.NET Console Application (or C# if you prefer it).
- Add a Web Reference to the service with the following URL: http://localhost/hello (or the correct URL if you have modified the default service location).
The following code shows how to access the WCF service exposed by the server:
Dim o As New HelloService.HelloService
System.Console.WriteLine("Response from WCF Service: {0}", o.sayHi())
Points of Interest
The example above shows how easy it is to access a WCF service. The client application can simply add a Web Reference to the service, and can use it just like any one would do with an ASP.NET web service.