Click here to Skip to main content
13,298,655 members (53,026 online)
Click here to Skip to main content
Add your own
alternative version


45 bookmarked
Posted 7 Oct 2008

Using WCF with Automatic Client Proxies

, 7 Oct 2008
Rate this:
Please Sign up or sign in to vote.
Using automatically generated proxies in WCF in a manner similar to .NET Remoting


Microsoft has produced Windows Communication Foundation (WCF) as the natural successor to its earlier .NET Web Service and Remoting technologies. From the documentation it initially seems like WCF just uses the same sort of manual client proxy generation as Web Services. However, WCF is equally capable of generating client proxies automatically in a similar manner to Remoting. This article seeks to redress the documentation imbalance.


Web Services were specifically designed for situations in which an interface was being publicly exposed outside the enterprise (where it was impractical to share interface code) and/or where technologies differ (for example, a Java client consuming a .NET Web Service). Clients are typically built by extracting interface metadata from a running Web Service, generating proxy interface code and building it into the client application.

Remoting was designed for use within an enterprise, typically on a single machine or enterprise LAN/WAN. The client(s) and server(s) are effectively part of the same overall application or system, sharing interface assemblies from which client proxies are automatically generated at runtime. Often both client and server are built as part of the same solution or in the same build process, a build which can be completed in a single pass.

Developers moving from Remoting must wonder how to generate WCF proxies automatically from shared assemblies as this subject is not well explained in the WCF documentation. There are strong reasons for keeping automatic proxies, including simpler build process and avoiding interface mismatch errors caused by missed manual proxy generation steps. Automatic proxies also give you common types between client and server which is essential if you want to share other code between the two.

How does WCF provide us with automatic client proxies? Here is a simple example.

The Service Interface

Firstly we define our interface (contract) and decorate it with the normal WCF service and operation attributes. This is then compiled into the shared assembly, in this case ICalculator.dll.

// ICalculator.cs

using System.ServiceModel;

namespace Calculator
    public interface ICalculator : IDisposable
        int Add (int a, int b);

This topic is well covered in the WCF documentation, but it is worth pointing out the use of IDisposable, the reasons for which I’ll come to later.

The Service Implementation

The example server here implements the calculator service and also provides a very simple console hosting application.

// CalculatorService.cs

using System;
using System.ServiceModel;

namespace Calculator

  // Implementation of CalculatorService

  public class CalculatorService : ICalculator

    public CalculatorService ()
      Console.WriteLine ("Constructing CalculatorService");

    public int Add (int a, int b)
      Console.WriteLine ("Call {0} Adding {1} and {2}", callNo++, a, b);
      return a+b;

    public void Dispose ()
      Console.WriteLine ("Disposing CalculatorService");

    private int callNo = 1;


  // Simple console service host

  public class TestProgram
    public static void Main ()
      ServiceHost svcHost = new ServiceHost (typeof (CalculatorService));
      Console.WriteLine ("Press a key to exit");


CalculatorService implements the shared ICalculator interface and logs its actions to the console. Note that it also implements IDiposable which provides a logical place to put any service clean-up code. The service also has a private counter callNo which illustrates its ability to hold state information.

The very simple console service hosting application above just starts up the ServiceHost and waits for the user to close it down (note that this is .NET 3.5 syntax. .NET 3.0 requires more endpoint detail). The ServiceHost listens for connections on the endpoints defined in the config file:

<!--<span class="code-comment">CalculatorService.config--></span>


      <service name="Calculator.CalculatorService">

        <endpoint address="net.tcp://localhost:5000/Calc"


                  contract="Calculator.ICalculator" />

        <endpoint address="net.pipe://localhost/Calc"


                  contract="Calculator.ICalculator" />

        <endpoint address="http://localhost:8081/Calc"


                  contract="Calculator.ICalculator" />

        <endpoint address="http://localhost:8080/Calc"


                  contract="Calculator.ICalculator" />




In this case I have exposed the same service using four endpoints, which correspond to the four bindings I will explore further below.

The Client Proxy

Since this article is about automatic client proxies, this is where the real action takes place. Firstly of course, the client program must reference the shared interface assembly ICalculator.dll so it can use the ICalculator type.

Creating a proxy does not use new. There are a number of options, but the way which most closely resembles conventional construction is:

ICalculator calc = new ChannelFactory<ICalculator>("TcpCalc").CreateChannel();

"TcpCalc" is the name of the remote endpoint to connect to, as defined in the client config file (below).

This statement creates both a proxy object of type ICalculator in the client and an instance of the CalculatorService service object on the server.

Having created the proxy, the client can simply invoke the methods of the remote service object:

int sum1 = calc.Add (1,2);
int sum2 = calc.Add (3,4);

There is a problem here. Even when we have finished with the client proxy, the channel to the server can remain open (for some protocols) and the remote service object will still exist, tying up valuable network and server resources. Only when the client proxy is garbage collected will the system clean-up.

Fortunately, it just so happens that proxy objects constructed by ChannelFactory always implement IDisposable as well as their generic type (ICalculator). Since ICalculator also happens to implement IDisposable we can simply dispose it:


This seems just like a proxy call to a corresponding service Dispose() operation and it appears to have this effect, but Dispose() has not been defined as an [OperationContract] so this cannot be. In reality the client Dispose() sends a 'close' message to the service and shuts down any open connections. On receipt of the close message the service calls Dispose() on the service object.

Of course it is good practice to employ the using block (or use Dispose() with try...finally):

using (ICalculator calc = new ChannelFactory<ICalculator>("TcpCalc").CreateChannel())
  int sum1 = calc.Add (1,2);
  int sum2 = calc.Add (3,4);
  . . .

IMHO this last code snippet really illustrates the way that WCF clients should look when both client and service originate within the same organisation.

Example Client

// CalculatorClient.cs

using System;
using System.ServiceModel;

namespace Calculator
  class TestClient

    static void Main ()

      // Create a proxy via TCP which is not closed until calc1 is garbage collected

      ICalculator calc1 = new ChannelFactory<ICalculator>("TcpCalc").CreateChannel();
      int sum1 = calc1.Add (1,2);
      int sum2 = calc1.Add (3,4);
      Console.WriteLine ("Sum1 = {0}  Sum2 = {1}", sum1, sum2);

      // Create a proxy via named pipe which explicitly closed by Dispose()

      ICalculator calc2 = new ChannelFactory<ICalculator>("PipeCalc").CreateChannel();
      sum1 = calc2.Add (5,6);
      sum2 = calc2.Add (7,8);
      Console.WriteLine ("Sum1 = {0}  Sum2 = {1}", sum1, sum2);

      // Create a proxy via WS HTTP binding which closes at the end of the 'using' block

      using (ICalculator calc3 = new ChannelFactory<ICalculator>(
        sum1 = calc3.Add (9,10);
        sum2 = calc3.Add (11,12);
        Console.WriteLine ("Sum1 = {0}  Sum2 = {1}", sum1, sum2);

      // Create a proxy via basic HTTP binding. Each call closes itself & 'using'
      // does nothing

      using (ICalculator calc4 = new ChannelFactory<ICalculator>(
        sum1 = calc4.Add (13,14);
        sum2 = calc4.Add (15,16);
        Console.WriteLine ("Sum1 = {0}  Sum2 = {1}", sum1, sum2);



A number of interesting points here:

  • In the case of calc1, the client proxy is not explicitly disposed. The log output from the service shows that Dispose() is only called later in program execution when calc1 is garbage collected.
  • Calc2 and calc3 are properly disposed after use and the corresponding service Dispose() is called immediately.
  • In the case of calc4 using the basic http binding, the service object is constructed and disposed for every call of Add(). Since there is a different service object for each method call, no state is retained between calls.
  • By contrast, services connected via the TCP, Named Pipe and WS HTTP bindings do retain state between method calls, as shown by the incrementing value of callNo. Given that behaviour varies with network transport then there is risk in using state and/or using the basic HTTP binding. That's for the developer to judge.

The corresponding client config file defines the four named service endpoints:

<!--<span class="code-comment">CalculatorClient.config--></span>


      <endpoint address="net.tcp://localhost:5000/Calc"



                name="TcpCalc" />

      <endpoint address="net.pipe://localhost/Calc"



                name="PipeCalc" />

      <endpoint address="http://localhost:8081/Calc"



                name="WsHttpCalc" />

      <endpoint address="http://localhost:8080/Calc"



                name="HttpCalc" />



In my experience, communications between clients and services within the enterprise is more common than exposing external interfaces to third parties. WCF provides an effective mechanism for this situation by automatically generating proxies using the ChannelFactory which is simpler, easier to code and less prone to manual build process errors. The lack of clear examples has hampered its adoption.

The lack of documentation may also have deterred some Remoting users from moving to WCF. While WCF automatic proxies don’t solve all the issues of migration, they do knock down one of the barriers to adoption. In many cases WCF is the effective successor to Remoting, exhibiting comparable performance and a similar choice of protocols.

Finally, some readers may be thinking that sharing types breaks the rules of SOA. This is not so. The 3rd tenet of SOA is "share schema/contract, not class". The shared interface types define the contract -- they are not classes (which would represent the implementation). I would argue that this approach is actually more service oriented than manually generated proxies. The first tenet of SOA is that boundaries should be explicit and the automatic creation of the client proxy via ChannelFactory is much more explicit than just using new with a manually generated proxy. In any event there is nothing to prevent the same service being accessed both internally using an automatic proxy and externally via a manual one.


First version, 06/10/08.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Tim Haynes
Web Developer
United Kingdom United Kingdom
No Biography provided

You may also be interested in...


Comments and Discussions

GeneralMy vote of 5 Pin
Sathish10126-Feb-13 4:20
memberSathish10126-Feb-13 4:20 
QuestionNice, will used it Pin
Glynn1-Sep-11 5:04
memberGlynn1-Sep-11 5:04 
QuestionWhat about Async Pattern ? Pin
fragmonster11-Apr-11 6:03
memberfragmonster11-Apr-11 6:03 
GeneralMy vote of 1 Pin
Amir Hosein Fadaei20-Oct-09 5:24
memberAmir Hosein Fadaei20-Oct-09 5:24 
QuestionWhat kind of error it is Pin
hamidzaidi16-Mar-09 8:43
memberhamidzaidi16-Mar-09 8:43 

I have developed a service which is selfhosted and when I teried to invoke the service via a another machine on a LAN I got following exceptions
Error : System.ServiceModel.Security.SecurityNegotiationException: The caller wa
s not authenticated by the service. ---> System.ServiceModel.FaultException: The
request for security token could not be satisfied because authentication failed
at System.ServiceModel.Security.SecurityUtils.ThrowIfNegotiationFault(Message
message, EndpointAddress target)
at System.ServiceModel.Security.SspiNegotiationTokenProvider.GetNextOutgoingM
essageBody(Message incomingMessage, SspiNegotiationTokenProviderState sspiState)

--- End of inner exception stack trace ---

Server stack trace:
at System.ServiceModel.Security.IssuanceTokenProviderBase`1.DoNegotiation(Tim
eSpan timeout)
at System.ServiceModel.Security.SspiNegotiationTokenProvider.OnOpen(TimeSpan
at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(Tim
eSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Security.CommunicationObjectSecurityTokenProvider.Open
(TimeSpan timeout)
at System.ServiceModel.Security.SecurityUtils.OpenCommunicationObject(ICommun
icationObject obj, TimeSpan timeout)
at System.ServiceModel.Security.SecurityUtils.OpenTokenProviderIfRequired(Sec
urityTokenProvider tokenProvider, TimeSpan timeout)
at System.ServiceModel.Security.SymmetricSecurityProtocol.OnOpen(TimeSpan tim
at System.ServiceModel.Security.WrapperSecurityCommunicationObject.OnOpen(Tim
eSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Security.SecurityProtocol.Open(TimeSpan timeout)
at System.ServiceModel.Channels.SecurityChannelFactory`1.ClientSecurityChanne
l`1.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.DoOperat
ion(SecuritySessionOperation operation, EndpointAddress target, Uri via, Securit
yToken currentToken, TimeSpan timeout)
at System.ServiceModel.Security.SecuritySessionSecurityTokenProvider.GetToken
Core(TimeSpan timeout)
at System.IdentityModel.Selectors.SecurityTokenProvider.GetToken(TimeSpan tim
at System.ServiceModel.Security.SecuritySessionClientSettings`1.ClientSecurit
ySessionChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)
at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.CallOpenOnce.System.ServiceMod
el.Channels.ServiceChannel.ICallOnce.Call(ServiceChannel channel, TimeSpan timeo
at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeS
pan timeout, CallOnceManager cascade)
at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan timeout)

at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean on
eway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan tim
at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean on
eway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCall
Message methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage req
Msg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgDa
ta, Int32 type)
at ConsoleApplication2.ServiceReference.INew.connect()
at ConsoleApplication2.Program.Main(String[] args) in C:\Users\MAI\Documents\
Visual Studio 2008\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs:l
ine 22

I am generating proxy but using add web services reference

Can somebody tell me what is the problem
GeneralSend me the complete solution not only .cs file Pin
n12prashant4-Mar-09 21:00
membern12prashant4-Mar-09 21:00 
GeneralDataContract not needed anymore in 3.5 SP1 Pin
wout de zeeuw8-Dec-08 0:22
memberwout de zeeuw8-Dec-08 0:22 
GeneralWhoooo! [modified] Pin
wout de zeeuw7-Dec-08 6:51
memberwout de zeeuw7-Dec-08 6:51 
GeneralRe: Whoooo! Pin
Tim Haynes16-Dec-08 7:18
memberTim Haynes16-Dec-08 7:18 
GeneralThank you very much! Pin
jonkman16-Oct-08 6:11
memberjonkman16-Oct-08 6:11 
GeneralUsing Statements, What Microsoft says. Pin
Jordon4Acclaim14-Oct-08 6:57
memberJordon4Acclaim14-Oct-08 6:57 
GeneralRe: Using Statements, What Microsoft says. Pin
Tim Haynes15-Oct-08 7:12
memberTim Haynes15-Oct-08 7:12 
GeneralRe: Using Statements, What Microsoft says. Pin
Jordon4Acclaim15-Oct-08 7:23
memberJordon4Acclaim15-Oct-08 7:23 
GeneralRules of SOA and Data Contracts Pin
Dave Elliott14-Oct-08 3:02
memberDave Elliott14-Oct-08 3:02 
GeneralRe: Rules of SOA and Data Contracts Pin
Tim Haynes15-Oct-08 7:57
memberTim Haynes15-Oct-08 7:57 
GeneralSome Corrections and Insight Pin
daniel...8-Oct-08 4:45
memberdaniel...8-Oct-08 4:45 
GeneralRe: Some Corrections and Insight Pin
Tim Haynes8-Oct-08 6:49
memberTim Haynes8-Oct-08 6:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171207.1 | Last Updated 7 Oct 2008
Article Copyright 2008 by Tim Haynes
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid