總結(jié)C#動態(tài)調(diào)用WCF接口的兩種方法
如何使用
1、第一種方式比較簡單,而且也是大家喜歡的,因為不需要任何配置文件就可解決,只需知道服務(wù)契約接口和服務(wù)地址就可以調(diào)用。
2、使用Invoke的方式,但是需要在調(diào)用客戶端配置WCF,配置后在Invoke類里封裝服務(wù)契約接口即可。
客戶端調(diào)用DEMO
//第一種方式
string url = "http://localhost:3000/DoubleService.svc";
IDoubleService proxy = WcfInvokeFactory.CreateServiceByUrl<IDoubleService>(url);
int result = proxy.Add(1, 3);
//第二種方式<br><br>int result1 = WCFInvoke.Invoke(t => t.Add(1, 3));<br><br>
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="NewBehavior">
<dataContractSerializer maxItemsInObjectGraph="65536000" />
</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="2147483647"
maxBufferPoolSize="524288"
maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="128" maxStringContentLength="2147483647" maxArrayLength="16384" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</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>
第一種調(diào)用方式
public class WcfInvokeFactory
{
#region WCF服務(wù)工廠
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("創(chuàng)建服務(wù)工廠出現(xiàn)異常.");
}
}
#endregion
#region 創(chuàng)建傳輸協(xié)議
/// <summary>
/// 創(chuàng)建傳輸協(xié)議
/// </summary>
/// <param name="binding">傳輸協(xié)議名稱</param>
/// <returns></returns>
private static Binding CreateBinding(string binding)
{
Binding bindinginstance = null;
if (binding.ToLower() == "basichttpbinding")
{
BasicHttpBinding ws = new BasicHttpBinding();
ws.MaxBufferSize = 2147483647;
ws.MaxBufferPoolSize = 2147483647;
ws.MaxReceivedMessageSize = 2147483647;
ws.ReaderQuotas.MaxStringContentLength = 2147483647;
ws.CloseTimeout = new TimeSpan(0, 30, 0);
ws.OpenTimeout = new TimeSpan(0, 30, 0);
ws.ReceiveTimeout = new TimeSpan(0, 30, 0);
ws.SendTimeout = new TimeSpan(0, 30, 0);
bindinginstance = ws;
}
else if (binding.ToLower() == "nettcpbinding")
{
NetTcpBinding ws = new NetTcpBinding();
ws.MaxReceivedMessageSize = 65535000;
ws.Security.Mode = SecurityMode.None;
bindinginstance = ws;
}
else if (binding.ToLower() == "wshttpbinding")
{
WSHttpBinding ws = new WSHttpBinding(SecurityMode.None);
ws.MaxReceivedMessageSize = 65535000;
ws.Security.Message.ClientCredentialType = System.ServiceModel.MessageCredentialType.Windows;
ws.Security.Transport.ClientCredentialType = System.ServiceModel.HttpClientCredentialType.Windows;
bindinginstance = ws;
}
return bindinginstance;
}
#endregion
}
第二種調(diào)用方式
public class WCFInvoke
{
/// <summary>
/// 你需要調(diào)用的服務(wù)契約
/// </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 < 1))
{
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 == 1))
{
Type key = genericArguments[0];
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();
}
}
}
}
總結(jié)
第一種方式比較常見,第二種方式是我參考另外一個項目中的寫法,其中的有一些細(xì)節(jié)我還沒有搞明白,實(shí)現(xiàn)了這個功能后還需要再看看這部分代碼,再消化消化。以上就是這篇文章的全部內(nèi)容,希望能給大家?guī)硪欢ǖ膸椭?,如果有疑問大家可以留言交流?/p>
上一篇:C# 6.0 新特性匯總
欄 目:C#教程
下一篇:C#如何給PDF文件添加水印
本文標(biāo)題:總結(jié)C#動態(tài)調(diào)用WCF接口的兩種方法
本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/6248.html
您可能感興趣的文章
- 01-10C#動態(tài)創(chuàng)建button的方法
- 01-10C#調(diào)用dos窗口獲取相關(guān)信息的方法
- 01-10c# ArrayList的使用方法小總結(jié)
- 01-10C#動態(tài)創(chuàng)建Access數(shù)據(jù)庫及密碼的方法
- 01-10C#實(shí)現(xiàn)子窗體與父窗體通信方法實(shí)例總結(jié)
- 01-10C#獲取動態(tài)生成的CheckBox值
- 01-10C#中DataGridView動態(tài)添加行及添加列的方法
- 01-10C#獲取客戶端相關(guān)信息實(shí)例總結(jié)
- 01-10同步調(diào)用和異步調(diào)用WebService
- 01-10C#調(diào)用WebService實(shí)例開發(fā)


閱讀排行
本欄相關(guān)
- 01-10C#通過反射獲取當(dāng)前工程中所有窗體并
- 01-10關(guān)于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實(shí)現(xiàn)txt定位指定行完整實(shí)例
- 01-10WinForm實(shí)現(xiàn)仿視頻播放器左下角滾動新
- 01-10C#停止線程的方法
- 01-10C#實(shí)現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實(shí)現(xiàn)讀取注冊表監(jiān)控當(dāng)前操作系統(tǒng)已
隨機(jī)閱讀
- 04-02jquery與jsp,用jquery
- 01-10C#中split用法實(shí)例總結(jié)
- 01-10SublimeText編譯C開發(fā)環(huán)境設(shè)置
- 01-10delphi制作wav文件的方法
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-11ajax實(shí)現(xiàn)頁面的局部加載
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 01-10使用C語言求解撲克牌的順子及n個骰子


