Disposing client after creation with WebChannelFactory
In my current production code, and according to documentation on msdn, the way to create a client is this
using (WebChannelFactory<IServiceInterface> cf
= new WebChannelFactory<IServiceInterface>("http://service.url"))
{
IServiceInterface client = cf.CreateChannel();
client.CallTheMethod();
}
given that I have this interface:
public interface IServiceInterface
{
void CallTheMethod();
}
However I noticed开发者_StackOverflow社区 that the object client created by the WebChannelFactory also implements IDisposable. So I want to dispose this object also. I didn't find any other way than:
using (WebChannelFactory<IServiceInterface> cf
= new WebChannelFactory<IServiceInterface>("http://service.url"))
using(IDisposable client = (IDisposable)cf.CreateChannel())
{
((IServiceInterface)client).CallTheMethod();
}
I find this ugly. So :
- Do I really need to dispose it ? I mean that may be it is disposed when you disposed the factory (if the factory keeps a reference to every object it has created maybe) ?
- If yes, do you have a better way ?
This is a very complex issue. Even by Microsoft's own admission, disposing of channel factories was a bad design which was changed multiple times so short answer is no, you need to use something alternative to it.
Here is an alternative method to disposing.
精彩评论