views:

268

answers:

2

Hello

As the title implies I am trying to get an understanding of why in WCF sometimes people choose to "generate proxies" vs using a ChannelFactory to manually create new channel instances. I have seen examples of each, but haven't really found any explainations of WHY you would go for one vs the other.

To be honest I have only ever worked with channels and the ChannelFactory from code I have inherited, ie:

IChannelFactory<IDuplexSessionChannel> channelFactory =
    binding.BuildChannelFactory<IDuplexSessionChannel>();

_duplexSessionChannel = channelFactory.CreateChannel(endpointAddress);

So why would I "generate a proxy"? What are the benifits and drawbacks?

Thanks in advance.

+1  A: 

Using a proxy is simpler and easier to understand. You get to deal in terms of simple things - classes and methods on those classes - instead of complex, network-related things like channels.

OTOH, this is not made easier by the design flaw in WCF that prevents the same simple use of a WCF proxy that we could do with ASMX proxies:

using (var client = new MyServiceClient())
{
}

If you use this pattern with WCF, you can lose the original exception when the block is exited due to an exception. client.Dispose() can throw an exception, which will overwrite the exception originally being thrown. A more complex pattern is required.

John Saunders
+1  A: 

The main difference is this:

  • generating a proxy only requires you to know the URL where the service resides. By generating the proxy, everything else (the service contract and the data contracts involved) will be determined by inspecting the metadata of the service

  • in order to directly create a ChannelFactory<T>, you must have direct access to the assembly that contains that service contract T for which you're generating a channel factory. This only ever works if you basically control both ends of the channel and you can share the assembly that contains those service contracts. Typically, with a third-party service, this won't be the case - with your own services, yes.

The second important point is this:

  • creating a generated proxy basically does the two steps that you would do - create a ChannelFactory<T>, and from that, create the actual channel - in a single constructor. You have no control over these two steps.

  • doing your own Channel creation is beneficial, since the creation of the ChannelFactory<T> is the expensive step - so yo could cache your channel factory instance somewhere. Creating and re-creating the actual channel from the factory is much less involved step which you can do more frequently

So if you do control both ends of the communication, service and client, you do have the option to share the service contracts in a separate assembly, and thus you have more options.

With most third-party services, you just simply don't have that option.

marc_s