TechBuzzPro

WCF Service Model: A Practical How-To Guide

· 6 min read · Apps & Browsers

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

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

  1. 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.cs and Service1.cs with sample code you can replace. Menu labels can differ slightly between Visual Studio versions and editions.
  2. Define the service contract. Open the interface file and mark it with [ServiceContract]. Mark each method you want exposed with [OperationContract]. For example:
    [ServiceContract]
    public interface ICalculator
    {
        [OperationContract]
        int Add(int a, int b);
    }
    Only methods carrying [OperationContract] are callable by clients; everything else stays internal.
  3. 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;
    }
  4. Configure an endpoint. An endpoint is the address, binding, and contract that clients connect to. In a service library, open App.config and check the <system.serviceModel> section. A minimal HTTP endpoint looks like:
    <system.serviceModel>
      <services>
        <service name="MyService.CalculatorService">
          <endpoint address=""
                    binding="basicHttpBinding"
                    contract="MyService.ICalculator" />
        </service>
      </services>
    </system.serviceModel>
    The name attribute must match the fully qualified class name, and the contract must match the fully qualified interface name. A mismatch here is the single most common cause of a service that starts but cannot be reached.
  5. 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();
    }
    ServiceHost reads the configuration file automatically. If you prefer code-based configuration, add endpoints with host.AddServiceEndpoint(typeof(ICalculator), new BasicHttpBinding(), "http://localhost:8080/calc") before calling Open().
  6. 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 serviceMetadata and serviceDebug behaviors are enabled. If the browser shows nothing, the host may still be working — check with a client before assuming failure.
  7. 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?wsdl from a Developer Command Prompt. Both produce a proxy class and a configuration file entry. Add Service Reference is the easier route inside Visual Studio.
  8. Call the service from the client. Instantiate the generated client, call the method, and close it:
    using (var client = new CalculatorClient())
    {
        Console.WriteLine(client.Add(2, 3));
    }
    Always close or abort the client in a finally block in production code; a faulted channel must be aborted, not closed.
  9. Add metadata exchange if you need it. For clients to discover the service, add a mex endpoint and a serviceMetadata behavior 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 name and contract attributes must be fully qualified and spelled exactly as in code.
  • Forgetting to open the host. A constructed ServiceHost does nothing until Open() 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 urlacl as administrator.
  • Closing a faulted client. Calling Close() on a channel that has thrown an exception raises another exception; use Abort() in that case.

Tips

  • Start with basicHttpBinding for interoperability and switch to wsHttpBinding or netTcpBinding only when you need the extra features.
  • Keep contracts small and version them carefully. Adding operations is usually safe; changing existing signatures breaks clients.
  • Enable includeExceptionDetailInFaults only during development. In production, return FaultContract types 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.Diagnostics tracing 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.