Getting Started with Windows Communication Foundation (WCF)
Windows Communication Foundation (WCF) is a robust framework for building service‑oriented applications that can communicate across platforms and networks. This guide walks you through creating your first WCF service using .NET Framework.
Prerequisites
- Visual Studio 2022 (or later) with .NET desktop development workload.
- .NET Framework 4.7.2 or later installed.
- Basic knowledge of C# and object‑oriented programming.
Step 1 – Create a WCF Service Library
- Open Visual Studio → Create a new project.
- Search for WCF Service Library and click Next.
- Name the project
CalculatorService
and click Create.
Step 2 – Define the Service Contract
Add an interface that describes the operations the service will expose:
using System.ServiceModel;
namespace CalculatorService
{
[ServiceContract]
public interface ICalculator
{
[OperationContract]
double Add(double a, double b);
[OperationContract]
double Subtract(double a, double b);
}
}
Step 3 – Implement the Service
Implement the contract in a class:
namespace CalculatorService
{
public class Calculator : ICalculator
{
public double Add(double a, double b) => a + b;
public double Subtract(double a, double b) => a - b;
}
}
Step 4 – Host the Service
For a quick start, host the service in a console application:
using System;
using System.ServiceModel;
using CalculatorService;
class Program
{
static void Main()
{
using var host = new ServiceHost(typeof(Calculator));
host.Open();
Console.WriteLine("Calculator service is running...");
Console.WriteLine("Press ENTER to exit");
Console.ReadLine();
host.Close();
}
}
Step 5 – Configure the Endpoint
Add the following to App.config
of the host project:
<configuration>
<system.serviceModel>
<services>
<service name="CalculatorService.Calculator">
<endpoint address="" binding="basicHttpBinding"
contract="CalculatorService.ICalculator"/>
<host>
<baseAddresses>
<add baseAddress="http://localhost:8080/CalculatorService"/>
</baseAddresses>
</host>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
Step 6 – Test the Service
Run the console host, then navigate to http://localhost:8080/CalculatorService?wsdl to view the service metadata.