WCF Service Model: A Practical How-To Guide
In this article
The Windows Communication Foundation (WCF) service model lets you build a service by defining a .NET interface marked with [ServiceContract], implementing it in a class, and hosting that class so clients can call its methods over SOAP, REST, or other transports. The shortest working path is: create a WCF Service Library or a console host, define the contract and implementation, add an endpoint in configuration, start a ServiceHost, then generate a client proxy with svcutil or add a service reference in Visual Studio. This guide walks through that path step by step, with the settings and gotchas that trip people up.
What You'll Need
- Visual Studio (any recent edition) with the .NET desktop development or WCF workload installed, or the .NET Framework SDK and a text editor if you prefer the command line.
- .NET Framework 4.x (WCF is a .NET Framework technology; it is not part of modern .NET, though the community CoreWCF project offers a port).
- Administrative rights on the machine if you plan to host under IIS or register an HTTP URL with
netsh. - A basic understanding of C# interfaces, classes, and XML configuration files.
Step-by-Step
- Create the project. In Visual Studio, choose File > New > Project, select WCF Service Library (or a Console App if you want a self-hosted service). A service library template gives you
IService1.csandService1.cswith sample code you can replace. Menu labels can differ slightly between Visual Studio versions and editions. - Define the service contract. Open the interface file and mark it with
[ServiceContract]. Mark each method you want exposed with[OperationContract]. For example:
Only methods carrying[ServiceContract] public interface ICalculator { [OperationContract] int Add(int a, int b); }[OperationContract]are callable by clients; everything else stays internal. - Implement the contract. Create a class that implements the interface. Keep the logic simple at first so you can confirm the plumbing works before adding complexity:
public class CalculatorService : ICalculator { public int Add(int a, int b) => a + b; } - Configure an endpoint. An endpoint is the address, binding, and contract that clients connect to. In a service library, open
App.configand check the<system.serviceModel>section. A minimal HTTP endpoint looks like:
The<system.serviceModel> <services> <service name="MyService.CalculatorService"> <endpoint address="" binding="basicHttpBinding" contract="MyService.ICalculator" /> </service> </services> </system.serviceModel>nameattribute must match the fully qualified class name, and thecontractmust match the fully qualified interface name. A mismatch here is the single most common cause of a service that starts but cannot be reached. - Host the service. For a console host, add a reference to
System.ServiceModel, then write:using (var host = new ServiceHost(typeof(CalculatorService))) { host.Open(); Console.WriteLine("Service running. Press Enter to stop."); Console.ReadLine(); }ServiceHostreads the configuration file automatically. If you prefer code-based configuration, add endpoints withhost.AddServiceEndpoint(typeof(ICalculator), new BasicHttpBinding(), "http://localhost:8080/calc")before callingOpen(). - Verify the service is listening. Run the host and confirm no exception is thrown. For an HTTP endpoint, open a browser and navigate to the base address; you should see the WCF help page if
serviceMetadataandserviceDebugbehaviors are enabled. If the browser shows nothing, the host may still be working — check with a client before assuming failure. - Generate a client proxy. In a separate client project, either right-click References > Add Service Reference and paste the base address, or run
svcutil.exe http://localhost:8080/calc?wsdlfrom a Developer Command Prompt. Both produce a proxy class and a configuration file entry. Add Service Reference is the easier route inside Visual Studio. - Call the service from the client. Instantiate the generated client, call the method, and close it:
Always close or abort the client in ausing (var client = new CalculatorClient()) { Console.WriteLine(client.Add(2, 3)); }finallyblock in production code; a faulted channel must be aborted, not closed. - Add metadata exchange if you need it. For clients to discover the service, add a
mexendpoint and aserviceMetadatabehavior in configuration. This is optional for a known contract but required for Add Service Reference to work against a self-hosted service.
Common Mistakes
- Missing
[OperationContract]. The method compiles but never appears in the WSDL, so the client cannot see it. - Name mismatches in configuration. The
service nameandcontractattributes must be fully qualified and spelled exactly as in code. - Forgetting to open the host. A constructed
ServiceHostdoes nothing untilOpen()is called. - Using types that cannot be serialized. Complex types passed across the boundary need
[DataContract]and[DataMember]on their members, or must be simple primitives. - Port or URL conflicts. Two services on the same port, or a URL reservation missing for HTTP, will throw at startup. Change the port or run
netsh http add urlaclas administrator. - Closing a faulted client. Calling
Close()on a channel that has thrown an exception raises another exception; useAbort()in that case.
Tips
- Start with
basicHttpBindingfor interoperability and switch towsHttpBindingornetTcpBindingonly when you need the extra features. - Keep contracts small and version them carefully. Adding operations is usually safe; changing existing signatures breaks clients.
- Enable
includeExceptionDetailInFaultsonly during development. In production, returnFaultContracttypes instead of raw exceptions. - Use the WCF Test Client (
wcftestclient.exe) shipped with Visual Studio to exercise a service without writing a client. - Log with
System.Diagnosticstracing or the built-in message logging in configuration when diagnosing binding problems.
Troubleshooting
If the host throws InvalidOperationException at startup, the configuration is almost always the cause: check that the service name matches the class, the contract matches the interface, and at least one endpoint is defined. If the client gets EndpointNotFoundException, confirm the host is running and the address in the client config matches the host's base address exactly, including the trailing slash. If you see AddressAlreadyInUseException, another process holds the port; pick a different one or stop the conflicting service. If Add Service Reference fails, verify the mex endpoint and serviceMetadata behavior are present, and that the service is running when you add the reference. If calls time out, check firewall rules and whether the binding's timeout settings are too short for the operation. When a serialization error appears, inspect the data contract types and ensure every member you need is marked [DataMember].
Frequently Asked Questions
Is WCF still supported?
Yes. WCF ships with .NET Framework 4.x, which remains supported on Windows. It is not included in modern .NET; CoreWCF is a separate community port for cross-platform use.
Can I use WCF without Visual Studio?
Yes. You can compile with csc.exe or MSBuild and host the service in a console app, Windows Service, or IIS. Visual Studio mainly provides templates and the Add Service Reference tooling.
What is the difference between a service contract and an operation contract?
The service contract marks the interface as callable over WCF. The operation contract marks individual methods within that interface as exposed operations. Only methods with both attributes (the interface attribute applies to all) are reachable.
Why does my client not see a method I added?
Most likely the method lacks [OperationContract], or the client proxy was generated before the change. Update the service reference and rebuild the client.
Can WCF services run on Linux?
Not with the .NET Framework implementation. CoreWCF provides a compatible server implementation for modern .NET on Linux, but it is a separate project with its own limitations.