ChannelFactory<T>.CreateChannel 如何工作?

Kam*_*Kam 5 c# wcf

如果我有一个接口:

public interface ISomething
{
    void DoAThing();
}
Run Code Online (Sandbox Code Playgroud)

然后我用 ChannelFactory 实例化它:

var channel = new ChannelFactory<ISomething>().CreateChannel
Run Code Online (Sandbox Code Playgroud)

我得到了一个可以使用的实例。

现在,要关闭它,我需要投射:

((IClientChannel)channel).Close
Run Code Online (Sandbox Code Playgroud)

或者

((IChannel)channel).Close
Run Code Online (Sandbox Code Playgroud)

或者

((ICommunicationObject)channel).Close
Run Code Online (Sandbox Code Playgroud)

我的ISomething接口没有继承任何这些接口。

那么CreateChannel方法返回什么样的对象,它是如何构造一个动态对象,该对象能够实现直到运行时才知道的接口?

Tew*_*ewr 2

ChannelFactory.CreateChannel()返回RealProxy的实现,它是一组通常称为透明代理或“远程处理”的工具的一部分,这是一种稍微过时的 pre-wcf 技术。为了创建实现该接口的实际类,它归结为一个名为RemotingServices .CreateTransparentProxy(...) 的内部框架级方法,我没有看过该方法,但它很可能是某种类构建器/发射器。

正如您所问的,您可能想自己做这样的事情。要在运行时实现接口,我推荐Castle Dynamic Proxy,它无需太多努力即可实现接口或抽象类。