Dynamic invocation of a WCF service requires only a *.SVC address.
1: Name space:
Using System.ServiceModel.Channels;
Using System.ServiceModel;
2: Create Access Class Invokecontext
public class Invokecontext
{
#region WCF Service Factory
public static T createwcfservicebyurl<t> (string url)
{
Return createwcfservicebyurl<t> (URL, "Wshttpbinding");
}
public static T createwcfservicebyurl<t> (String url,string Bing)
{
if (string. IsNullOrEmpty (URL)) throw new NotSupportedException ("This URL isn ' t Null or empty!");
EndpointAddress address = new endpointaddress (URL);
Binding binding = Createbinding (Bing);
Channelfactory<t> factory = new channelfactory<t> (binding, address);
Return factory. CreateChannel ();
}
#endregion
#region Create a transport protocol
<summary>
Create a transport protocol
</summary>
<param name= "binding" > Transfer Protocol name </param>
<returns></returns>
private static binding createbinding (String binding)
{
Binding bindinginstance = null;
if (binding. ToLower () = = "BasicHttpBinding")
{
BasicHttpBinding ws = new BasicHttpBinding ();
Ws. MaxReceivedMessageSize = 65535000;
Bindinginstance = WS;
}
else if (binding. ToLower () = = "NetNamedPipeBinding")
{
netnamedpipebinding ws = new netnamedpipebinding ();
Ws. MaxReceivedMessageSize = 65535000;
Bindinginstance = WS;
}
else if (binding. ToLower () = = "NetPeerTcpBinding")
{
netpeertcpbinding ws = new netpeertcpbinding ();
Ws. MaxReceivedMessageSize = 65535000;
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 () = = "Wsdualhttpbinding")
{
wsdualhttpbinding ws = new wsdualhttpbinding ();
Ws. MaxReceivedMessageSize = 65535000;
Bindinginstance = WS;
}
else if (binding. ToLower () = = "WebHttpBinding")
{
WebHttpBinding ws = new webhttpbinding ();
Ws. MaxReceivedMessageSize = 65535000;
Bindinginstance = WS;
}
else if (binding. ToLower () = = "WSFederationHttpBinding")
{
wsfederationhttpbinding ws = new wsfederationhttpbinding ();
Ws. MaxReceivedMessageSize = 65535000;
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
}
3.T is called the interface type, which is the instance of the class returned by WCF, because my WCF is interface-based, so add a connection type to judge, call directly write: Interface iface = Invokecontext.createwcfservicebyurl <Interface> (URL);
Dynamically invoking a WCF service