利用泛型反射在运行时动态创建WCF客户端

如果我们知道WCF服务的url,binding,contractType,我们可以使用下面的代码来创建一个WCF客户端对象:

ChannelFactory<ITaskService>.CreateChannel(new BasicHttpBinding(),new EndpointAddress(url));

但上面的代码里面我们没有办法做到BasicHttpBinding的可配置,此时我们可以使用下面的代码配合App.Config实现Binding信息的可配置:

ChannelFactory<ITaskService>.CreateChannel(new BasicHttpBinding("BasicHttpBinding_TaskService"),new EndpointAddress(url));
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_TaskService" closeTimeout="00:01:00"
openTimeout
="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
allowCookies
="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize
="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding
="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy
="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead
="4096" maxNameTableCharCount="16384" />
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None"
realm
="" />
</security>
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
</configuration>

但以上做法都是静态完成的,我们有没有办法实现动态创建WCF客户端对象呢?

    var service1 = GetWcfClient(url, new BasicHttpBinding(), typeof(ITaskService)) as ITaskService;
var service2 = GetWcfClient(url, new BasicHttpBinding("BasicHttpBinding_TaskService"), typeof(ITaskService)) as ITaskService;
    public static object GetWcfClient(string url, Binding binding, Type contractType)
{
Type channelFactoryGenericType = typeof(ChannelFactory<>).MakeGenericType(new Type[] { contractType });
MethodInfo method = channelFactoryGenericType.GetMethod("CreateChannel", new Type[] { typeof(Binding), typeof(EndpointAddress) });
return method.Invoke(null, new Object[] { binding, new EndpointAddress(url) });
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_TaskService" closeTimeout="00:01:00"
openTimeout
="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:10:00"
allowCookies
="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
maxBufferSize
="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
messageEncoding
="Text" textEncoding="utf-8" transferMode="Buffered"
useDefaultWebProxy
="true">
<readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
maxBytesPerRead
="4096" maxNameTableCharCount="16384" />
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None"
realm
="" />
</security>
</binding>
</basicHttpBinding>
</bindings>
</system.serviceModel>
</configuration>

 

你可能感兴趣的:(WCF)