WCF通道具體應(yīng)用技巧分享
WCF中的通道應(yīng)用在實(shí)際編程中是一個(gè)非常重要的操作步驟。我們今天將會通過對WCF通道的使用技巧進(jìn)行一個(gè)詳細(xì)的分析,希望可以讓大家從中獲得一些幫助,已解決在實(shí)際編程中出現(xiàn)的一些問題。
我們可以用WCF通道(channel)代替靜態(tài)代理(svcutil proxy),直接調(diào)用服務(wù)操作。ChannelFactory< T> 允許我們在運(yùn)行時(shí)動態(tài)創(chuàng)建一個(gè)代理與服務(wù)進(jìn)行交互。
- 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
- }
我們需要從配置文件中獲取一個(gè)端點(diǎn)配置名稱,將其提交給 ChannelFactory< T> 構(gòu)造方法,也可以直接使用相應(yīng)的綁定和地址對象作為參數(shù)。然后,調(diào)用 CreateChannel() 方法獲取動態(tài)生成代理對象的引用。有兩種方法關(guān)閉代理,將WCF通道轉(zhuǎn)型成 IDisposable,并調(diào)用 Dispose() 方法關(guān)閉代理;或者轉(zhuǎn)型成 ICommunicationObject,調(diào)用 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通道對象除了實(shí)現(xiàn)服務(wù)契約接口外,還實(shí)現(xiàn)了 System.ServiceModel.IClientChannel。
- public interface IClientChannel : IContextChannel, IChannel,
ICommunicationObject, IDisposable ...- {
- }
除創(chuàng)建 ChannelFactory< T> 對象實(shí)例外,我們還可以直接使用靜態(tài)方法 CreateChannel() 來創(chuàng)建代理。不過這需要我們提供端點(diǎn)地址和綁定對象。
- 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通道的相關(guān)應(yīng)用的介紹。
【編輯推薦】