TIP: Using Proxies and ChannelFactory in WCF

Thursday Feb 26th 2009 by SM Altaf

Look at the two methods of talking to WCF services and when to use them. Also see sample code to use the ChannelFactory in C#.

Proxies vs ChannelFactory

If you've used WCF services before, you know that you can add a reference to the service either by using svcutil.exe or letting Visual Studio do it for you (which in turn uses svcutil.exe).

Although using the proxy classes is the most common way, it's not always the best way.

Remember that not all WCF services are created the same. In some cases, you may have a service that is tightly bound to the client application—in other words, you may have a service that's only going to be used by a few applications, ever.

In such a case, it makes sense to reference the Interface DLL directly and use ChannelFactory to call your methods using that. One significant advantage of the ChannelFactory route is that it gives you access to methods that wouldn't otherwise be available if you used svcutil.exe.

However, if you have a service that you know is going to be used by several applications or is generic enough to be used in several places, you'll want to continue using the generated proxy classes.

It's worth keeping in mind that, when you generate a proxy class using svcutil.exe, it's doing almost the same thing as ChannelFactory behind the scenes, with the difference that the Interface is inferred from the metadata from your WCF service.

Using ChannelFactory

Start by referencing the Interface assembly. By default, your WCF service will have the interfaces in the same assembly as the service code. You should move the interface code out to another assembly so that it's reusable by the service and your client. Even if you're not going to use ChannelFactory, it's good practice to keep your Interface in a separate assembly.

Next, create the ChannelFactory like this:

ChannelFactory<IService1> channel =
   new ChannelFactory<IService1>("bindingName");
IService1 client = channel.CreateChannel();

And finally, call your method.

Mobile Site | Full Site
Copyright 2017 © QuinStreet Inc. All Rights Reserved