How to: Use the ChannelFactory
The generic ChannelFactory class is used in advanced scenarios that require the creation of a channel factory that can be used to create more than one channel.
To create and use the ChannelFactory class
-
Build and run an Windows Communication Foundation (WCF) service. For more information, see Designing and Implementing Services, Configuring Services, and Hosting Services.
-
Use the ServiceModel Metadata Utility Tool (Svcutil.exe) to generate the contract (interface) for the client.
-
In the client code, use the ChannelFactory class to create multiple endpoint listeners.
Example
using System; using System.ServiceModel; // This code generated by svcutil.exe. [ServiceContract()] interface IMath { [OperationContract()] double Add(double A, double B); } public class Math : IMath { public double Add(double A, double B) { return A + B; } } public sealed class Test { static void Main() { // Code not shown. } public void Run() { // This code is written by an application developer. // Create a channel factory. BasicHttpBinding myBinding = new BasicHttpBinding(); EndpointAddress myEndpoint = new EndpointAddress("http://localhost/MathService/Ep1"); ChannelFactory<IMath> myChannelFactory = new ChannelFactory<IMath>(myBinding, myEndpoint); // Create a channel. IMath wcfClient1 = myChannelFactory.CreateChannel(); double s = wcfClient1.Add(3, 39); Console.WriteLine(s.ToString()); ((IClientChannel)wcfClient1).Close(); // Create another channel. IMath wcfClient2 = myChannelFactory.CreateChannel(); s = wcfClient2.Add(15, 27); Console.WriteLine(s.ToString()); ((IClientChannel)wcfClient2).Close(); myChannelFactory.Close(); } }
Based on the Example above you might want to make a new interface:
interface IMathChannel : IMath, IClientChannel
{
}
Once you have that you can do this with your ChannelFactory:
ChannelFactory<IMathChannel> myChannelFactory = new ChannelFactory<IMathChannel>(myBinding, myEndpoint);
Now when you want to close your channel you don't have to deal with the cast. you can just call:
wcfClient1.Close();
- 10/16/2011
- Blake R. Bosin