WCF通道具体应用技巧分享

WCF中的通道应用在实际编程中是一个非常重要的操作步骤。我们今天将会通过对WCF通道的使用技巧进行一个详细的分析,希望可以让大家从中获得一些帮助,已解决在实际编程中出现的一些问题。

我们提供的服务有:做网站、成都网站设计、微信公众号开发、网站优化、网站认证、渭南ssl等。为超过千家企事业单位解决了网站和推广的问题。提供周到的售前咨询和贴心的售后服务,是有科学管理、有技术的渭南网站制作公司

我们可以用WCF通道(channel)代替静态代理(svcutil proxy),直接调用服务操作。ChannelFactory< T> 允许我们在运行时动态创建一个代理与服务进行交互。

 
 
 
  1. public class ContractDescription  
  2. {  
  3. public Type ContractType {get;set;}  
  4. //More members  
  5. }  
  6. public class ServiceEndpoint  
  7. {  
  8. public ServiceEndpoint(ContractDescription contract, 
    Binding binding, EndpointAddress address);  
  9. public EndpointAddress Address {get;set;}  
  10. public Binding Binding {get;set;}  
  11. public ContractDescription Contract {get;}  
  12. //More members  
  13. }  
  14. public abstract class ChannelFactory : ...  
  15. {  
  16. public ServiceEndpoint Endpoint {get;}  
  17. //More members  
  18. }  
  19. public class ChannelFactory< T> : ChannelFactory,...  
  20. {  
  21. public ChannelFactory(ServiceEndpoint endpoint);  
  22. public ChannelFactory(string configurationName);  
  23. public ChannelFactory(Binding binding, EndpointAddress 
    endpointAddress);  
  24. public static T CreateChannel(Binding binding, 
    EndpointAddress endpointAddress);  
  25. public T CreateChannel( );  
  26. //More Members  

我们需要从配置文件中获取一个端点配置名称,将其提交给 ChannelFactory< T> 构造方法,也可以直接使用相应的绑定和地址对象作为参数。然后,调用 CreateChannel() 方法获取动态生成代理对象的引用。有两种方法关闭代理,将WCF通道转型成 IDisposable,并调用 Dispose() 方法关闭代理;或者转型成 ICommunicationObject,调用 Close() 方法。

 
 
 
  1. ChannelFactory< IMyContract> factory = new ChannelFactory
    < IMyContract>( );  
  2. IMyContract proxy1 = factory.CreateChannel( );  
  3. using(proxy1 as IDisposable)  
  4. {  
  5. proxy1.MyMethod( );  
  6. }  
  7. IMyContract proxy2 = factory.CreateChannel( );  
  8. proxy2.MyMethod( );  
  9. ICommunicationObject channel = proxy2 as ICommunicationObject;  
  10. Debug.Assert(channel != null);  
  11. channel.Close( ); 

注: WCF通道对象除了实现服务契约接口外,还实现了 System.ServiceModel.IClientChannel。

 
 
 
  1. public interface IClientChannel : IContextChannel, IChannel, 
    ICommunicationObject, IDisposable ...  
  2. {  

除创建 ChannelFactory< T> 对象实例外,我们还可以直接使用静态方法 CreateChannel() 来创建代理。不过这需要我们提供端点地址和绑定对象。

 
 
 
  1. Binding binding = new NetTcpBinding( );  
  2. EndpointAddress address = new EndpointAddress
    ("net.tcp://localhost:8000");  
  3. IMyContract proxy = ChannelFactory< IMyContract>.
    CreateChannel(binding, address);  
  4. using(proxy as IDisposable)  
  5. {  
  6. proxy1.MyMethod( );  

以上就是我们对WCF通道的相关应用的介绍。

本文标题:WCF通道具体应用技巧分享
文章URL:http://www.hantingmc.com/qtweb/news3/400653.html

网站建设、网络推广公司-创新互联,是专注品牌与效果的网站制作,网络营销seo公司;服务项目有等

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联