直接渠道使用与使用代理?

直接渠道使用与使用代理?

问题描述:

正如标题所示,我试图了解为什么在WCF中有时人们选择生成代理,而不是使用ChannelFactory手动创建新的通道实例。我已经看到了每个示例,但还没有真正找到为什么您会选择一个而另一个的任何解释。

As the title implies I am trying to get an understanding of why in WCF sometimes people choose to "generate proxies" vs using a ChannelFactory to manually create new channel instances. I have seen examples of each, but haven't really found any explanations of WHY you would go for one vs the other.

说实话,我只与通道和我继承的代码中的 ChannelFactory< T> ,即:

To be honest I have only ever worked with channels and the ChannelFactory<T> from code I have inherited, ie:

IChannelFactory<IDuplexSessionChannel> channelFactory =
    binding.BuildChannelFactory<IDuplexSessionChannel>();

_duplexSessionChannel = channelFactory.CreateChannel(endpointAddress);

那我为什么要生成代理?优点和缺点是什么?

So why would I "generate a proxy"? What are the benefits and drawbacks?

主要区别是:


  • 生成代理仅需要您知道服务所在的URL。通过生成代理,将通过检查服务的元数据来确定其他所有内容(服务合同和涉及的数据合同)

  • generating a proxy only requires you to know the URL where the service resides. By generating the proxy, everything else (the service contract and the data contracts involved) will be determined by inspecting the metadata of the service

,以便直接创建 ChannelFactory< T> ,您必须直接访问包含该服务合同 T 的程序集重新生成渠道工厂。仅当您基本上控制了通道的两端并且可以共享包含这些服务合同的程序集时,这才有效。通常,对于第三方服务,情况并非如此-对于您自己的服务,是的。

in order to directly create a ChannelFactory<T>, you must have direct access to the assembly that contains that service contract T for which you're generating a channel factory. This only ever works if you basically control both ends of the channel and you can share the assembly that contains those service contracts. Typically, with a third-party service, this won't be the case - with your own services, yes.

第二个要点是:


  • 创建生成的代理基本上可以完成您要执行的两个步骤-创建 ChannelFactory< T> ,然后在单个构造函数中创建实际的通道。您无法控制这两个步骤。

  • creating a generated proxy basically does the two steps that you would do - create a ChannelFactory<T>, and from that, create the actual channel - in a single constructor. You have no control over these two steps.

创建自己的频道是有好处的,因为创建 ChannelFactory< T> 是昂贵的步骤-因此您可以将您的通道工厂实例缓存在某个地方。从工厂创建和重新创建实际渠道所涉及的步骤要少得多,因此您可以更频繁地进行操作

doing your own Channel creation is beneficial, since the creation of the ChannelFactory<T> is the expensive step - so yo could cache your channel factory instance somewhere. Creating and re-creating the actual channel from the factory is much less involved step which you can do more frequently

如果您确实控制通信,服务和客户端的两端,那么您确实可以选择在单独的程序集*享服务合同,因此可以有更多选择。

So if you do control both ends of the communication, service and client, you do have the option to share the service contracts in a separate assembly, and thus you have more options.

对于大多数第三方服务,您只是没有选择。

With most third-party services, you just simply don't have that option.