Windows Communication Foundation (WCF) Basics
Windows Communication Foundation (WCF) is a framework for building service‑oriented applications. In .NET Framework 3.5, WCF introduces several enhancements, including simplified configuration, support for RESTful services, and better integration with ASP.NET.
Key Concepts
- Service Contract – Defines the operations a service exposes.
- Data Contract – Describes the data types used in messages.
- Binding – Specifies how to communicate (protocol, encoding, transport).
- Endpoint – Combination of address, binding, and contract.
- Hosting – Where the service runs (IIS, WAS, self‑hosted).
Creating a Simple Service
The following example demonstrates a basic WCF service that returns a greeting.
// Service contract
[ServiceContract]
public interface IGreetingService
{
[OperationContract]
string GetGreeting(string name);
}
// Service implementation
public class GreetingService : IGreetingService
{
public string GetGreeting(string name)
{
return $"Hello, {name}!";
}
}
Configuring the Service (app.config)
<system.serviceModel>
<services>
<service name="GreetingService">
<endpoint address="" binding="basicHttpBinding" contract="IGreetingService"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/GreetingService"/>
</baseAddresses>
</host>
</service>
</services>
</system.serviceModel>
Consuming the Service (Client)
ChannelFactory<IGreetingService> factory =
new ChannelFactory<IGreetingService>(new BasicHttpBinding(),
new EndpointAddress("http://localhost:8080/GreetingService"));
IGreetingService proxy = factory.CreateChannel();
Console.WriteLine(proxy.GetGreeting("World"));
((IClientChannel)proxy).Close();
factory.Close();
Running the Service
To self‑host the service, add the following code to a console application:
using (ServiceHost host = new ServiceHost(typeof(GreetingService)))
{
host.Open();
Console.WriteLine("Service is running...");
Console.ReadLine();
}
For detailed guidance, explore the linked sections in the navigation pane.