如何在不对名称进行硬编码的情况下将接口类型传递给ChannelFactory
问题描述:
我使用反射调用WCF服务.我在使用ChannelFactory,绑定和端点地址创建代理的地方.
让我们认为我的服务合同"名称为ISeravice1.
我正在创建代理并以这种方式调用特定方法:
Hi,
I calling a WCF Service using reflections . Where I''m creating a Proxy by using ChannelFactory ,binding and endpoint address.
Let us think that My ServiceContract Name is ISeravice1.
I''m creating a Proxy and calling a specific method in this way:
using (ChannelFactory<T> cf = new ChannelFactory<T>(binding, uri))
{
object oProxy = cf.CreateChannel();
Type oType = oProxy.GetType();
MethodInfo oMeth = oType.GetMethod(method);
oMeth.Invoke(oProxy, args);
}
在上面的代码中,我需要通过< T>作为我的ServiceContact,即IService1.
如果我有很多服务合同,则需要全部指定,因此我需要删除服务合同名称的硬编码.
问候,
Ramana
In the above code I need to pass <T> as my ServiceContact that is IService1.
If I have many Service Contracts then I need to specify all , so I need to remove hardcoding of name of Service Contract.
Regards,
Ramana
答
由于您始终在使用反射,因此可以使用反射实例化通用ChannelFactory类.
Since you''re using reflection anyways, you could instantiate the generic ChannelFactory class using reflection.
public static object CreateGeneric(Type generic, Type innerType, params object[] args)
{
System.Type specificType = generic.MakeGenericType(new System.Type[] { innerType });
return Activator.CreateInstance(specificType, args);
}
var contract = typeof(ICoolWebService); // or whatever
var cf = CreateGeneric(typeof(ChannelFactory), contract);
信用 [
Credit[^]