WCF通道具體應用技巧分享
WCF中的通道應用在實際編程中是一個非常重要的操作步驟。我們今天將會通過對WCF通道的使用技巧進行一個詳細的分析,希望可以讓大家從中獲得一些幫助,已解決在實際編程中出現(xiàn)的一些問題。
我們可以用WCF通道(channel)代替靜態(tài)代理(svcutil proxy),直接調用服務操作。ChannelFactory< T> 允許我們在運行時動態(tài)創(chuàng)建一個代理與服務進行交互。
- public class ContractDescription
- {
- public Type ContractType {get;set;}
- //More members
- }
- public class ServiceEndpoint
- {
- public ServiceEndpoint(ContractDescription contract,
Binding binding, EndpointAddress address);- public EndpointAddress Address {get;set;}
- public Binding Binding {get;set;}
- public ContractDescription Contract {get;}
- //More members
- }
- public abstract class ChannelFactory : ...
- {
- public ServiceEndpoint Endpoint {get;}
- //More members
- }
- public class ChannelFactory< T> : ChannelFactory,...
- {
- public ChannelFactory(ServiceEndpoint endpoint);
- public ChannelFactory(string configurationName);
- public ChannelFactory(Binding binding, EndpointAddress
endpointAddress);- public static T CreateChannel(Binding binding,
EndpointAddress endpointAddress);- public T CreateChannel( );
- //More Members
- }
我們需要從配置文件中獲取一個端點配置名稱,將其提交給 ChannelFactory< T> 構造方法,也可以直接使用相應的綁定和地址對象作為參數(shù)。然后,調用 CreateChannel() 方法獲取動態(tài)生成代理對象的引用。有兩種方法關閉代理,將WCF通道轉型成 IDisposable,并調用 Dispose() 方法關閉代理;或者轉型成 ICommunicationObject,調用 Close() 方法。
- ChannelFactory< IMyContract> factory = new ChannelFactory
< IMyContract>( );- IMyContract proxy1 = factory.CreateChannel( );
- using(proxy1 as IDisposable)
- {
- proxy1.MyMethod( );
- }
- IMyContract proxy2 = factory.CreateChannel( );
- proxy2.MyMethod( );
- ICommunicationObject channel = proxy2 as ICommunicationObject;
- Debug.Assert(channel != null);
- channel.Close( );
注: WCF通道對象除了實現(xiàn)服務契約接口外,還實現(xiàn)了 System.ServiceModel.IClientChannel。
- public interface IClientChannel : IContextChannel, IChannel,
ICommunicationObject, IDisposable ...- {
- }
除創(chuàng)建 ChannelFactory< T> 對象實例外,我們還可以直接使用靜態(tài)方法 CreateChannel() 來創(chuàng)建代理。不過這需要我們提供端點地址和綁定對象。
- Binding binding = new NetTcpBinding( );
- EndpointAddress address = new EndpointAddress
("net.tcp://localhost:8000");- IMyContract proxy = ChannelFactory< IMyContract>.
CreateChannel(binding, address);- using(proxy as IDisposable)
- {
- proxy1.MyMethod( );
- }
以上就是我們對WCF通道的相關應用的介紹。
【編輯推薦】