views:

1845

answers:

1

Consider the following code which is typcial of many ChannelFactory examples:

WSHttpBinding myBinding = new WSHttpBinding();
EndpointAddress myEndpoint = new EndpointAddress(
   ConfigurationSettings.AppSettings["HelloWorldServiceURL"]);  

ChannelFactory<IHelloWorldService> myChannelFactory = 
   new ChannelFactory<IHelloWorldService>(myBinding, myEndpoint);

IHelloWorldService proxy = myChannelFactory.CreateChannel();
((IClientChannel)proxy).Open();
HelloWorldDataContract dc = proxy.SayHello();
((IClientChannel)proxy).Close();

Note that when proxy.Open() is called, both the the channel's state and the ChannelFactory's state become "Opened". When proxy.Close() is called, the channel's state becomes "closed", but the ChannelFactory's state remains "Opened".

Should one be closing the ChannelFactory as well? I don't seem to see this in many examples. Also, if possible please explain the difference between having a channel open vs having a channel factory open.

Additionally, I am aware of the IDisposable issue, so it probably can be ignored for the sake of this question unless it has direct impact on the answer.

+4  A: 

As you know, the ChannelFactory creates the client channel based on configuration. You may want to create multiple client channels from an existing factory (to the same endpoint as that is locked). If you're done using the factory to create channels, there is no reason not to close it.

But, why might you want to keep it open? Here's an interesting article on WCF clients that says:

Checking the value of the System.ServiceModel.ICommunicationObject.State property is a race condition and is not recommended to determine whether to reuse or close a channel.

Rather than reuse a channel, you might want to simply create a new one with the channel factory. More on the client architecture is here.

JP Alioto