随着WCF越来越被更多的人认可,使用也越来越广泛。但在使用过程中也确实存在着某些让开发者不放便的地方,例如:
using (ChannelFactory<ICompute> channelFactory = new ChannelFactory<ICompute>( " ICompute ")) { ICompute proxy = channelFactory.CreateChannel(); proxy.Add( 1, 1); }
像这样的写法让人看起来有些不舒服。因此,为了方便使用还是有必要整理一下的。
public class ServiceClient { private static ServiceClient _instance; /// <summary> /// 对象实例 /// </summary> public static ServiceClient Instance { get { return _instance ?? (_instance = new ServiceClient()); } } /// <summary> /// 通讯发生错误触发 /// </summary> public static event EventHandler<ServiceFaultedArges> Faulted; /// <summary> /// 服务终结点 /// </summary> public static String EndpointName { get; set; } /// <summary> /// 执行服务方法,带返回值 /// </summary> /// <typeparam name="TChannel"> 契约接口 </typeparam> /// <typeparam name="TReturn"> 返回类型 </typeparam> /// <param name="func"> 执行方法委托 </param> /// <returns></returns> public TReturn Execute<TChannel, TReturn>(Func<TChannel, TReturn> func) { var errorMsg = ""; try { var channel = GetChannel<TChannel>(); var result = func(channel); try { ((IClientChannel)channel).Close(); } catch { ((IClientChannel)channel).Abort(); } return result; } catch (CommunicationException ex) { errorMsg = ex.Message; } catch (TimeoutException ex) { errorMsg = ex.Message; } catch (Exception ex) { errorMsg = ex.Message; } Faulted( this, new ServiceFaultedArges() { ErrorMsg =errorMsg}); return default(TReturn); } /// <summary> /// 执行服务方法,不带返回值 /// </summary> /// <typeparam name="TChannel"> 契约接口 </typeparam> /// <param name="func"> 执行方法委托 </param> public void Execute<TChannel>(Action<TChannel> func) { var errorMsg = string.Empty; try { var channel = GetChannel<TChannel>(); func(channel); try { ((IClientChannel)channel).Close(); } catch { ((IClientChannel)channel).Abort(); } } catch (CommunicationException ex) { errorMsg = ex.Message; } catch (TimeoutException ex) { errorMsg = ex.Message; } catch (Exception ex) { errorMsg = ex.Message; } Faulted( this, new ServiceFaultedArges() { ErrorMsg = errorMsg }); } /// <summary> /// 初始化代理 /// </summary> /// <typeparam name="TChannel"></typeparam> /// <returns></returns> private static TChannel GetChannel<TChannel>() { var chanFactory = new ChannelFactory<TChannel>(EndpointName); // if (Faulted != null) chanFactory.Faulted += Faulted; return chanFactory.CreateChannel(); } }
客户端调用:
static void Main( string[] args) { Common.WCF.ServiceClient.EndpointName = " ICompute1 "; Common.WCF.ServiceClient.Faulted += Faulted; var result= Common.WCF.ServiceClient.Instance.Execute<Snail.WCFServices.Contracts.ICompute, double>(ent => ent.Add( 1, 2)); Console.Write(result); Console.ReadKey(); } private static void Faulted( object sender, ServiceFaultedArges e) { Console.Write(e.ErrorMsg); }
这样使用起来就方便多了,对于异常的处理和写日志也变得轻松,也不再动不动就整个页面就黄了...哈哈
以上为本人拙见,如有发现问题欢迎指正,如有更好的方法也请赐教,相互学习,一起成长...