How to consume WCF Service using Channel Factory

A Channel Factory is implemented by the IChannelFactory Interface and their associated channels are used by the initiators of a communication pattern. The Channel Factory class is useful when you want to share a common service contract DLL between the client and the server.
When to use Channel Factory

The Channel Factory class is used to construct a channel between the client and server without creating a Proxy. In some of the cases in which your service is tightly bound with to the client application, we can use an interface DLL directly and with the help of a Channel Factory, call a method. The advantage of the Channel Factory route is that it gives you access method(s) that wouldn’t be available if you use svcutil.exe.

Channel Factory is also useful when you do not share more than just the service contract with a client. If you know that your entity will not change frequently than it is better to use a Channel Factory than a Proxy.

ChannelFactory<T> takes a generic parameter of the service type (it must be a service contract interface) to create a channel. Because ChannelFactory only requires knowledge of the service contract, it makes good design sense to put service/data contracts in separate assemblies from service implementations. This way, you can safely distribute contract assemblies to third parties who wish to consume services, without the risk of disclosing their actual implementation.

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://159.195.1.28/MathService/Service.svc”);
ChannelFactory myChannelFactory = new ChannelFactory(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();
}
}

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.
This entry was posted in General, MS CRM 2011 and tagged , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *