Reputation: 471
Using WCF ChannelFactory CreateChannel method of my custom interface -
ChannelFactory<MyServiceInterface> myFactory=
new ChannelFactory<MyServiceInterface>(binding,endpoint);
MyServiceInterface clientInterface = myFactory.CreateChannel();
Reading a lot around the web, looks like I want to close my channel properly like -
private void ProperlyDisposeChannel(ICommunicationObject comObj)
{
bool success = false;
if (comObj == null || comObj.State == CommunicationState.Closed)
{
return;
}
try
{
if (comObj.State != CommunicationState.Faulted)
{
comObj.Close();
success = true;
}
}
catch (Exception e)
{
//optionally log exception
}
finally
{
if (!success)
{
try
{
comObj.Abort();
}
catch (Exception e)
{
//do not retry to abort, optionally log
}
}
}
}
So I am trying to cast my channel to IClientChannel (or maybe IChannel), but VS is warning me - Suspicious cast - there is no type in the solution that inherits both MyServiceInterface and System.ServiceModel.IClientChannel
I was under the impression that the proxy returned by the factory automatically implements IClientChannel. Am I wrong? What is this warning about? And what should I cast my channel to? And maybe my ProperlyDisposeChannel method should accept IClientChannel instead of ICommunicationObject (I prefer ICOmmuminationObject bec it will work for other objects too)
So I'm trying the following line which gives me the warning -
ProperlyDisposeChannel((IChannel)clientInterface);
or ProperlyDisposeChannel((IClientChannel)clientInterface);
Upvotes: 2
Views: 2218
Reputation: 28530
You can use the ICommunicationObject
to do the close or abort - I do that all the time.
Simply change your call to:
ProperlyDisposeChannel((ICommunicationObject)clientInterface);
And it will work as expected.
Upvotes: 0
Reputation: 1186
Despite the suspicious warning you got, you can do an explicit cast. Indeed the CreateChannel() signature returns the interface Type of your service but is also inheriting the IChannel interface under the wood.
This makes sense as the method cannot obviously return 2 types, allowing to use directly your service.
This is an implementation choice, it could have been returning, let's say, public interface IChannel<T> : IChannel { T Instance {get;} }
Upvotes: 1