如何使用

1、第一种方式比较简单,而且也是大家喜欢的,因为不需要任何配置文件就可解决,只需知道服务契约接口和服务地址就可以调用。

2、使用Invoke的方式,但是需要在调用客户端配置WCF,配置后在Invoke类里封装服务契约接口即可。

//第一种方式
string url = "http://localhost:3000/DoubleService.svc";
IDoubleService proxy = WcfInvokeFactory.CreateServiceByUrl<IDoubleService>(url);
int result = proxy.Add(, ); //第二种方式
int result1 = WCFInvoke.Invoke(t => t.Add(, ));
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="NewBehavior">
<dataContractSerializer maxItemsInObjectGraph="" />
</behavior>
</endpointBehaviors>
</behaviors>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IDoubleService"
closeTimeout="01:00:00"
openTimeout="01:00:00"
sendTimeout="01:00:00"
receiveTimeout="01:00:00"
maxBufferSize=""
maxBufferPoolSize=""
maxReceivedMessageSize="">
<readerQuotas maxDepth="" maxStringContentLength="" maxArrayLength="" maxBytesPerRead="" maxNameTableCharCount="" />
</binding>
</basicHttpBinding>
<netMsmqBinding>
<binding name="NetMsmqBinding_IAsyncSender">
<security mode="None" />
</binding>
</netMsmqBinding>
</bindings>
<client> <endpoint address="http://localhost:3000/DoubleService.svc"
binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IDoubleService"
contract="DoubleStone.WebHost.IDoubleService"
name="BasicHttpBinding_IDoubleService" /> </client>
</system.serviceModel>

第一种调用方式

public class WcfInvokeFactory
{
#region WCF服务工厂
public static T CreateServiceByUrl<T>(string url)
{
return CreateServiceByUrl<T>(url, "basicHttpBinding");
} public static T CreateServiceByUrl<T>(string url, string bing)
{
try
{
if (string.IsNullOrEmpty(url)) throw new NotSupportedException("This url is not Null or Empty!");
EndpointAddress address = new EndpointAddress(url);
Binding binding = CreateBinding(bing);
ChannelFactory<T> factory = new ChannelFactory<T>(binding, address);
return factory.CreateChannel();
}
catch (Exception ex)
{
throw new Exception("创建服务工厂出现异常.");
}
}
#endregion #region 创建传输协议
/// <summary>
/// 创建传输协议
/// </summary>
/// <param name="binding">传输协议名称</param>
/// <returns></returns>
private static Binding CreateBinding(string binding)
{
Binding bindinginstance = null;
if (binding.ToLower() == "basichttpbinding")
{
BasicHttpBinding ws = new BasicHttpBinding();
ws.MaxBufferSize = ;
ws.MaxBufferPoolSize = ;
ws.MaxReceivedMessageSize = ;
ws.ReaderQuotas.MaxStringContentLength = ;
ws.CloseTimeout = new TimeSpan(, , );
ws.OpenTimeout = new TimeSpan(, , );
ws.ReceiveTimeout = new TimeSpan(, , );
ws.SendTimeout = new TimeSpan(, , ); bindinginstance = ws;
}
else if (binding.ToLower() == "nettcpbinding")
{
NetTcpBinding ws = new NetTcpBinding();
ws.MaxReceivedMessageSize = ;
ws.Security.Mode = SecurityMode.None;
bindinginstance = ws;
}
else if (binding.ToLower() == "wshttpbinding")
{
WSHttpBinding ws = new WSHttpBinding(SecurityMode.None);
ws.MaxReceivedMessageSize = ;
ws.Security.Message.ClientCredentialType = System.ServiceModel.MessageCredentialType.Windows;
ws.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
bindinginstance = ws;
}
return bindinginstance; }
#endregion
}

第二种调用方式

public class WCFInvoke
{
/// <summary>
/// 你需要调用的服务契约
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="func"></param>
/// <returns></returns>
public static T Invoke<T>(Func<IDoubleService, T> func)
{
IServiceInvoker serviceInvoker=new WCFServiceInvoker();
return serviceInvoker.InvokeService(func);
}
} public interface IServiceInvoker
{
void InvokeService<T>(Action<T> invokeHandler) where T : class;
TReslt InvokeService<T, TReslt>(Func<T, TReslt> invokeHandler) where T : class;
} public class WCFServiceInvoker:IServiceInvoker
{
private static readonly ChannelFactoryManager FactoryManager = new ChannelFactoryManager(); private static readonly ClientSection ClientSection =
ConfigurationManager.GetSection("system.serviceModel/client") as ClientSection;     public void InvokeService<T>(Action<T> invokeHandler) where T : class
    {
KeyValuePair<string, string> endpointNameAddressPair = GetEndpointNameAddressPair(typeof(T));
var arg = FactoryManager.CreateChannel<T>(endpointNameAddressPair.Key, endpointNameAddressPair.Value);
var obj2 = (ICommunicationObject)arg;
try
{
invokeHandler(arg);
}
finally
{
try
{
if (obj2.State != CommunicationState.Faulted)
{
obj2.Close();
}
}
catch
{
obj2.Abort();
}
}
} public TReslt InvokeService<T, TReslt>(Func<T, TReslt> invokeHandler) where T : class
{
KeyValuePair<string, string> endpointNameAddressPair = GetEndpointNameAddressPair(typeof(T));
var arg = FactoryManager.CreateChannel<T>(endpointNameAddressPair.Key, endpointNameAddressPair.Value);
var obj2 = (ICommunicationObject)arg;
try
{
return invokeHandler(arg);
}
finally
{
try
{
if (obj2.State != CommunicationState.Closed || obj2.State != CommunicationState.Faulted)
{
obj2.Close();
}
}
catch
{
obj2.Abort();
}
}
} private KeyValuePair<string, string> GetEndpointNameAddressPair(Type serviceContractType)
{
var configException =
new ConfigurationErrorsException(
string.Format(
"No client endpoint found for type {0}. Please add the section <client><endpoint name=\"myservice\" address=\"http://address/\" binding=\"basicHttpBinding\" contract=\"{0}\"/></client> in the config file.",
serviceContractType));
if (((ClientSection == null) || (ClientSection.Endpoints == null)) || (ClientSection.Endpoints.Count < ))
{
throw configException;
}
foreach (ChannelEndpointElement element in ClientSection.Endpoints)
{
if (element.Contract == serviceContractType.ToString())
{
return new KeyValuePair<string, string>(element.Name, element.Address.AbsoluteUri);
}
}
throw configException;
}
}
public class ChannelFactoryManager : IDisposable
{
private static readonly Dictionary<Type, ChannelFactory> Factories = new Dictionary<Type, ChannelFactory>();
private static readonly object SyncRoot = new object(); public void Dispose()
{
Dispose(true);
} public virtual T CreateChannel<T>() where T : class
{
return CreateChannel<T>("*", null);
} public virtual T CreateChannel<T>(string endpointConfigurationName) where T : class
{
return CreateChannel<T>(endpointConfigurationName, null);
} public virtual T CreateChannel<T>(string endpointConfigurationName, string endpointAddress) where T : class
{
T local = GetFactory<T>(endpointConfigurationName, endpointAddress).CreateChannel();
((IClientChannel)local).Faulted += ChannelFaulted;
return local;
} protected virtual ChannelFactory<T> GetFactory<T>(string endpointConfigurationName, string endpointAddress)
where T : class
{
lock (SyncRoot)
{
ChannelFactory factory;
if (!Factories.TryGetValue(typeof(T), out factory))
{
factory = CreateFactoryInstance<T>(endpointConfigurationName, endpointAddress);
Factories.Add(typeof(T), factory);
}
return (factory as ChannelFactory<T>);
}
} private ChannelFactory CreateFactoryInstance<T>(string endpointConfigurationName, string endpointAddress)
{
ChannelFactory factory = null;
factory = !string.IsNullOrEmpty(endpointAddress) ? new ChannelFactory<T>(endpointConfigurationName, new EndpointAddress(endpointAddress)) : new ChannelFactory<T>(endpointConfigurationName); factory.Faulted += FactoryFaulted;
factory.Open();
return factory;
} private void ChannelFaulted(object sender, EventArgs e)
{
var channel = (IClientChannel)sender;
try
{
channel.Close();
}
catch
{
channel.Abort();
}
} private void FactoryFaulted(object sender, EventArgs args)
{
var factory = (ChannelFactory)sender;
try
{
factory.Close();
}
catch
{
factory.Abort();
}
Type[] genericArguments = factory.GetType().GetGenericArguments();
if ((genericArguments.Length == ))
{
Type key = genericArguments[];
if (Factories.ContainsKey(key))
{
Factories.Remove(key);
}
}
} protected virtual void Dispose(bool disposing)
{
if (disposing)
{
lock (SyncRoot)
{
foreach (Type type in Factories.Keys)
{
ChannelFactory factory = Factories[type];
try
{
factory.Close();
}
catch
{
factory.Abort();
}
}
Factories.Clear();
}
}
}
}

最新文章

  1. SQL中distinct的用法
  2. Linux 计划任务 访问网页
  3. ios7自带的晃动效果
  4. 解决SDK Manager无法更新问题
  5. Asterix and Obelix
  6. DEV控件自定义排序实现
  7. EJB相关的面试题
  8. Java常见运算符整理
  9. Navicat永久激活步骤,激活工具,解决注册码无效的问题
  10. spring jdbctemplate调用存储过程,返回list对象
  11. PyCharm 安装package matplotlib为例
  12. jq文件上传及下载
  13. 在Microsoft Dynamic 365/2016环境使用LinqPad查询数据(不使用linqpad Microsoft Dynamic 365 Driver)
  14. 开发组件:ZeroMQ
  15. es6中对象转数组,转map
  16. 怎么删除桌面右键&quot;打开好桌道壁纸&quot;
  17. bootstrap模态框嵌套、tabindex属性、去除阴影
  18. java servlet jsp 导入boostrap css js
  19. luogu 6月月赛 E 「数学」约数个数和
  20. CentOS最常用命令

热门文章

  1. SSH框架的简单含义
  2. [Codeforces 8D] Two Friends
  3. POJ 2112 Optimal Milking(二分图匹配)
  4. 【最大流】【Dinic】bzoj1711 [Usaco2007 Open]Dingin吃饭
  5. python3 开发面试题(%s和format的区别)5.31
  6. 1.6(java学习笔记)static关键字
  7. linux下目录大小为什么是4K?一个目录下最多有个多少个子目录?最多有多少个文件?ls -l显示的内容中total到底是什么?
  8. flask的文件上传和下载
  9. javascript快速入门18--样式
  10. javascript数据类型检测方法