Skip to content


A WCF Proxy from Scratch: No Service Reference, No App.Config Files

June 10, 2012

After 4 years of working as a  Silverlight Presentation Layer developer consuming WCF services in an n-tier Client/Server environment, I started learning to develop WCF Services in March of 2012.  At first reading books, then taking a good class in April, followed by coding learning projects every week.  Early on in this process creating a client proxy with the Visual Studio “Add Service Reference” command seemed like magic.  It raised a few key questions like “Is there a way to create a client proxy programmatically?” and “How does a proxy work?”  This blog article is the outcome of answering that question, here in June 2012, as I move from the WCF basics into more advanced areas.

Yes, it possible to create a proxy programmatically (and there are several different approaches, only one of which is shown here).  And it is also useful.  For example, imagine that you had a Silverlight or WPF client in a Prism environment. You want to dynamically load an assembly with MEF that contained extensions to an existing service or data contract.  Using a programmatically generated proxy, rather than an “Update Service Reference” command in Visual Studio, would greatly aid in this.

This article focuses on the simplest approach that can possibly work to programmatically generating a client proxy, so as to facilitate learning.  This is likely not the approach you would use in a real life situation, but when you understand the example presented here you’ll have no problem developing much better real life programmatically generated proxies.


The Server needs:

  •         Service Contract(s).
  •         Service implementation.
  •         Data Contract(s) for complex types.  Simple types like int, string, etc. do not need Data Contracts.
  •         Service Endpoint – The service Address, Binding, and Contract.
  •         Service Host – It runs the service implementation and causes the WCF runtime to create a Server-side Channel Stack to operate the Service Endpoint.  The Channel Stack communicates with the Client Proxy, and processes all messages going back and forth, including serializing/deserializing all objects identified in the Data Contracts.

The Client needs – Almost the same things as the server:

  •         Service Contract(s) – Same as Server.
  •         Data Contract(s) – Almost the same as Server.
  •         Service Endpoint – Same as Server.
  •         Proxy  – Contains all of the above, plus ServiceClient class that causes the WCF   runtime to create a Client-side Channel Stack to process all messages on the Client Side.  Using Data Contracts, the Channel Stack serializes/deserializes all objects received from/sent to the Server.

Note both the Client and Server need the same Service Contract, Data Contract(s), and Endpoints.  Indeed the Service Contract can be copied and pasted from the Server files into the Client Proxy file.  This is described below.  The information in the Endpoint is placed into the Server’s Service Host and also the Client Proxy Class, also described below

Using the Ingredients

The Visual Studio solution containing this code example is in the file named WCFProxyFromScratchColorsService on OneDrive.  Just click the link, then click “Download” on OneDrive’s top menu bar when it appears.

The below screen shot of the Solution Explorer for this solution shows where the various ingredients are located.

Notice that there is no Client Service Reference.  And there are no App.config files in the Client nor Service.  This is because all the information normally in a Service Reference and App.config file is hand coded.  This code can be found in the following files.

  •         The Service Contract is located on the Server in ColorsService.ServiceInterface.cs, and on the Client in ColorsClientConsole.Proxy.cs.  They both contain exact dulicate copies of the Service Contract.
  •         The Data Contract is located on the Server in ColorsBusinessLayer.ColorsBusinessObjects.cs, and on the Client in ColorsClientConsole.Proxy.cs.  They both contain exactly the same members.  The Server-side Data Contract can use automatic properties or full properties.  However, the Client-side Data Contract must use full properties, with private backing variables.  Full properties are required by the Client deserializer.  Without them you will get null assigned to each field. 
  •         The Service Host is located in ColorsServiceHostConsole.Program.cs.  This is where the WCF Channel is created and maintained that runs the service on the Server-side.  This is done with the WCF ServiceHost<T> type.
  •         The Proxy in ColorsClientConsole.Proxy.cs also contains the code that creates the Client-side WCF Channel, in addition to the Service and Data Contracts.  The Client-side WCF channel is in the class ColorsServiceClient in ColorsClientConsole.Proxy.cs.  This class uses the WCF type ChannelFactory to create the channel and allow the Client code to communicate with the Service. 

Here is the code for the Client-side ColorsClientConsole.Proxy.cs:

using System;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;

namespace ColorsClientConsole
<summary> /// Service Contract
 /// </summary>
    [ServiceContract(Namespace = "GeorgeStevens.Software.Developer/2012/05")]
    public interface IColorsService
        string GetColorBrushString(string colorName);

        ColorSwatch GetColor(string colorName);

<summary> /// Data Contract
 /// </summary>
    [DataContract(Namespace = "GeorgeStevens.Software.Developer.Schemas/2012/05")]
    public class ColorSwatch
        public int Id
            get { return _id; }
            set { _id = value; }
        private int _id;

        public string Name
            get { return _name; }
            set { _name = value; }
        private string _name;

        public string Description
            get { return _description; }
            set { _description = value; }
        private string _description;

        public string ARGBString
            get { return aRGBString; }
            set { aRGBString = value; }
        private string aRGBString;

<summary> /// The Client Proxy class
 /// </summary>
    public class ColorsServiceClient
        public static IColorsService GetProxy()
            EndpointAddress ep = new EndpointAddress("http://localhost:8732/ColorsService/ColorsServiceImpl");
            IColorsService proxy =
                ChannelFactory.CreateChannel(new BasicHttpBinding(), ep);
            return proxy;

The above file shows that the hand coded programmatic way of generating a WCF proxy is quite straight forward.  It removes a lot of the complexity from the xml and code generated by Add Service Reference so that one can see exactly what is going on.

Try placing a breakpoint on one of the setters in the Data Contract.  It will be hit when the deserializer is initializing the object’s properties.

It would be useful to compare the above code to that generated by Add Service Reference.  I’ll leave that as an exercise for the reader.  This will give you a deeper insight into what is going on in the proxy.  One thing that you will notice is a generated proxy uses ClientBase<T> rather than ChannelFactory to generate the channel.  I used ChannelFactory since its main purpose is to allow the creation of proxies programmatically, on the fly.

Here is the code for the Server-side ColorsServiceHostConsole.Program.cs.  Compare this code and its Address, Binding, and Contract with those in the ColorsServiceClient code, above.

static void Main(string[] args)
     Console.WriteLine("ColorsServiceHost Console:\n");

<summary> /// The Service Host -- Contains the Serivce's address, binding, and contract.
 /// Constructs a channel that processes messages to/from the Client and serializes/deserializes
 /// data going to/from the Client according to the DataContract defined above.
 /// </summary>
     // Args = Service type, base address(es).
     using(ServiceHost host = new ServiceHost(typeof(ColorsService.ColorsServiceImpl), new Uri"http://localhost:8732/ColorsService"))
          // Args = Contract, Binding, Address (within the above base address)
          host.AddServiceEndpoint(typeof(ColorsService.IColorsService), new BasicHttpBinding(), "ColorsServiceImpl");
          Console.WriteLine("\nPress ENTER to terminate this ColorsServiceHost Console.");

Download the example solution and play with it.  To run the solution:

  • First, start the Service Host.  Set the start up project to the ColorsServiceHostConsole project, then press F5.
  • Second, start the ColorsClientConsole by hovering over this project in the Solution Explorer, right clicking, the selecting Debug > Start New Instance.  This will launch the Client app which immediately launches some service operations and reports back the results to the display.

P.S.  You will have to start Visual Studio as Administrator if you are not logged in as an Admin.  Otherwise you will get a WCF exception when the Service Host starts.

A Better Way

If you want to use this technique in production software, I suggest you create a separate project in the Shared folder in the above Solution Explorer screen shot.  The project in this folder will contain WCF data and service contracts that are shared by the Clients and Services.  Perhaps call the project SharedContracts.  Then have both the Service and the Client reference the SharedContracts dll.  This way, there will be only 1 copy of all service and data contracts to maintain, rather than the duplicate copies of each that is shown in this example for the purpose of demonstration only.

I hope you find this useful.

George Stevens

Creative Commons License
dotnetsilverlightprism blog by George Stevens is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
Based on a work at

One Comment
  1. Derk permalink

    Thank you so much for this post! And double thanks for source code. Simple and effective and very helpful!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: