C#動態呼叫WCF介面

小y發表於2017-06-13

這種方式比較簡單,而且也是大家喜歡的,因為不需要任何配置檔案就可解決,只需知道服務契約介面和服務地址就可以呼叫。

string url = "http://localhost:3000/DoubleService.svc";
IDoubleService proxy = WcfInvokeFactory.CreateServiceByUrl<IDoubleService>(url);
int result = proxy.Add(1, 3);

需要用到的類

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 = 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
   }

不需要任何配置檔案,適合配置多個wcf,然後在後臺win服務動態呼叫的使用場景。

相關文章