Search code examples
c#dispose

Why is the Dispose() method not available on my IDisposable object?


I have a class with this field:

private WcfChannelFactory<IPrestoService> _channelFactory;

In the Dispose() method, I'm doing this:

if (_channelFactory != null) { _channelFactory.Dispose(); }

But that produces an error:

Cannot access explicit implementation of IDisposable.Dispose

After doing some research, it appears that I can dispose this way:

if (_channelFactory != null) { (_channelFactory as IDisposable).Dispose(); }

I don't understand two things:

  1. Why isn't Dispose() available? WcfChannelFactory<T> derives from ChannelFactory<T>, which derives from ChannelFactory, which implements IDisposable. Yet ChannelFactory doesn't have a Dispose() method. How is this possible?

  2. If I could (should?) simply call Close() on _channelFactory, why doesn't the XML documentation state that Close() will also call Dispose()? Maybe it won't? This is confusing.


Solution

    1. As the Dispose method is implemented explicilty for the IDisposable interface, you can only see the method when you have a reference of the type IDisposable. The method is there, but you can't see it when you have a reference of a different type. It's similar to how a private method is only visible from code within the class itself, although it's always there.

    2. The Close method won't call Dispose for this class. The method doesn't close the factory, it starts an asynchronous closing process. When the Close method exits, the closing process is not finished, so the object can't be disposed at that time.