#region
|
|
using System;
|
using System.ServiceModel;
|
|
#endregion
|
|
namespace CSFrameworkV5.WebRef
|
{
|
/// <summary>
|
/// WCF客户端代理层-基类
|
/// </summary>
|
/// <typeparam name="T"></typeparam>
|
public class WCF_Base<T> where T : class
|
{
|
private void CloseService(ICommunicationObject svc)
|
{
|
try
|
{
|
//查看连接状态,关闭WCF
|
var state = svc.State; //创建WCF通道,默认State=Opened;
|
|
svc.Close();
|
|
//svc.Close();//测试关闭状态下,调用Close
|
}
|
catch
|
{
|
}
|
}
|
|
/// <summary>
|
/// 执行WCF方法
|
/// </summary>
|
/// <param name="action">调用WCF接口核心逻辑</param>
|
protected void Excute(Action<T> action)
|
{
|
T svc = null;
|
|
try
|
{
|
svc = WCFFactory.Create<T>();
|
action(svc);
|
CloseService(svc as ICommunicationObject); //关闭WCF服务
|
}
|
catch (Exception ex)
|
{
|
if (svc != null) CloseService(svc as ICommunicationObject);
|
|
throw ex;
|
}
|
}
|
|
/// <summary>
|
/// 执行WCF方法
|
/// </summary>
|
/// <typeparam name="R">数据类型</typeparam>
|
/// <param name="action">调用WCF接口核心逻辑</param>
|
/// <returns></returns>
|
protected R Excute<R>(Func<T, R> action)
|
{
|
T svc = null;
|
|
try
|
{
|
svc = WCFFactory.Create<T>(); //创建WCF接口实例
|
var result = action(svc); //调用接口逻辑
|
CloseService(svc as ICommunicationObject); //关闭WCF服务
|
return result;
|
}
|
catch (Exception ex)
|
{
|
if (svc != null) CloseService(svc as ICommunicationObject);
|
|
throw ex;
|
}
|
}
|
|
/// <summary>
|
/// 执行指定WCF接口的方法
|
/// </summary>
|
/// <typeparam name="M">WCF接口</typeparam>
|
/// <typeparam name="R">数据类型</typeparam>
|
/// <param name="action">调用WCF接口核心逻辑</param>
|
/// <returns></returns>
|
protected R Excute<R, M>(Func<M, R> action) where M : class
|
{
|
M svc = null;
|
|
try
|
{
|
svc = WCFFactory.Create<M>(); //创建WCF接口实例
|
var result = action(svc); //调用接口逻辑
|
CloseService(svc as ICommunicationObject); //关闭WCF服务
|
return result;
|
}
|
catch (Exception ex)
|
{
|
if (svc != null) CloseService(svc as ICommunicationObject);
|
|
throw ex;
|
}
|
}
|
}
|
}
|