Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the ChannelFactory<T>.CreateChannel work?

Tags:

c#

wcf

If I have an interface:

public interface ISomething
{
    void DoAThing();
}

Then I instantiate it with the ChannelFactory:

var channel = new ChannelFactory<ISomething>().CreateChannel

I get an instance I can use.

Now, to close it I need to cast:

((IClientChannel)channel).Close

or

((IChannel)channel).Close

or

((ICommunicationObject)channel).Close

My ISomething interface does not inherit any of these interfaces.

So what kind of an object did the CreateChannel method return and how did it construct a dynamic object that was capable of implementing an interface it had no idea about until run time?

like image 341
Kam Avatar asked Nov 01 '22 14:11

Kam


1 Answers

ChannelFactory.CreateChannel() returns an implementation of RealProxy, which is part of a set of tools usually referred to as TransparentProxy or "Remoting", which is a slightly outdated pre-wcf tech. For creating the actual class that implements the interface, it comes down to an internal framework-level method called RemotingServices.CreateTransparentProxy(...), that I haven't looked at but which is most likely a class builder/emitter of some sorts.

As you're asking, you might want to do something like this yourself. To implement an interface at runtime I recommend Castle Dynamic Proxy which implements interfaces or abstract class without too much effort.

like image 166
Tewr Avatar answered Nov 15 '22 06:11

Tewr