How does a WCF proxy implement ICommunicationObject if it's methods aren't visible?
Asked Answered
T

2

6

How does a WCF channel (created via ChannelFactory) implement ICommunicationObject, but doesn't expose the Close() method, for example, unless you cast the proxy to ICommunicationObject? Does that make sense?

I got to thinking about that on the way home today and couldn't figure it out in my head. Maybe I'm asking the wrong question? Maybe I'm asking a stupid question? :)

Is it some kind of ninja trick?

Through answered 7/8, 2012 at 22:48 Comment(0)
J
6

This is done via Explicit Interface Implementation.

Suppose you have an interface, like so:

public interface IFoo
{
     void Foo();
}

You can implement this normally:

public class Bar : IFoo
{
     public void Foo() {} // Implicit interface implementation
}

Alternatively, you can implement the interface members explicitly, which requires the cast:

public class Baz : IFoo
{
     void IFoo.Foo() {} // This will require casting the object to IFoo to call
}

This can be very useful at times. For example, it is often done to implement IDisposable in classes where the preferred API would be to call .Close(), for example. By implementing IDisposable explicitly, you "hide" the Dispose() method, but still allow the class instance to be used via a using statement.

Johnathanjohnathon answered 7/8, 2012 at 22:50 Comment(1)
Thanks, Reed and Dan! First post wins.Through
R
2

The Channel class implements the ICommunicationObject interface explicitly. Here's an example demonstrating the difference between explicit interface implementation and implicit interface implementation:

internal interface IExample
{
    void DoSomething();
}

class ImplicitExample : IExample
{
    public void DoSomething()
    {
        // ...
    }
}

class ExplicitExample : IExample
{
    void IExample.DoSomething()
    {
        // ...
    }
}

class Consumer
{
    void Demo()
    {
        var explicitExample = new ExplicitExample();
        // explicitExample.DoSomething(); <-- won't compile
        ((IExample)explicitExample).DoSomething(); // <-- compiles

        var implicitExample = new ImplicitExample();
        implicitExample.DoSomething(); // <-- compiles
    }
}

Here is a link to the an MSDN article on this subject: http://msdn.microsoft.com/en-us/library/ms173157.aspx

Raine answered 7/8, 2012 at 22:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.