使用反射调用 WCF 函数 [英] Invoking WCF functions using Reflection
问题描述
我有一个使用 NetTcpBinding
的 WCF 应用程序.我想使用 System.Reflection
命名空间中的 Methodbase.Invoke
调用 WCF 服务中的函数.换句话说,我想通过传递一个 String
作为函数名称来动态调用一个函数.
I have a WCF application that is using NetTcpBinding
. I want to invoke the functions in WCF service using Methodbase.Invoke
from the System.Reflection
namespace. In other words I want to Dynamically call a Function by passing a String
as the Function name.
反射非常适用于 Web 服务或 Windows 应用程序或任何 DLL 或类.所以当然有一种方法可以为 WCF 做到这一点,但我无法找到方法.
Reflection works great for Web Service or a Windows application or any DLL or class. So there is certainly a way to do this for WCF but I am unable to find out how.
我得到了程序集名称,然后输入一切正常,但因为我们无法创建接口类的实例.我尝试使用绑定打开 WCF 连接并尝试传递该对象,但它抛出异常:
I am getting the Assembly Name then it's type everything fine but as we cannot create an instance of the Interface class. I tried to open the WCF connection using the binding and tried to pass that object but it's throwing an exception as:
对象与目标类型不匹配."
"Object does not match target type."
我已经打开连接并传递了对象,类型仅为接口.我不知道是我尝试了错误的方法还是使用了错误的方法.知道我如何才能做到这一点吗?
I have opened the connection and passed the object and type is of interface only. I don't know whether I'm trying the wrong thing or am using the wrong way. Any idea how I can accomplish this?
NetTCPBinding
都是在打开连接时正确给出的.我正在使用 WCF 作为使用 NETTCPBinding
的 Windows 服务.
The NetTCPBinding
all are properly given while opening the connection. I am using WCF as a Windows Service using NETTCPBinding
.
推荐答案
在调用方法时传递了正确的实例.此实例是通过对 ChannelFactory 的基于接口的调用创建的代理对象.我在一个 hello world 风格的应用程序上尝试了你的技术并得到了预期的结果.我在您的代码示例中没有看到的一件事是您如何初始化参数.那可能是个问题.我相信您对 Type.GetType 的调用可能会导致您收到错误.请注意,我在 Proxy 对象上调用了 GetType.我在下面包含了我的示例代码,它调用了一个将一个参数作为整数的函数 GetData....
You are passing the correct instance when you invoke your method. This instance is the proxy object created via the interface-based call to ChannelFactory. I tried your technique on a hello world style application and got the expected results. One thing I don't see in your code example is how you initialize the parameters. That could be a problem. I believe think that your call to Type.GetType may be causing the error you are receiving. Notice I call GetType on the Proxy object. I include my sample code below that calls a Function GetData that takes one argument as an integer. ...
Dim myFactory As ChannelFactory(Of SimpleService.IService1)
myFactory = New ChannelFactory(Of SimpleService.IService1)(myBinding, myEndpoint)
oProxy = myFactory.CreateChannel()
'commented out version that does same call without reflection
' oProxy.GetData(3)
Dim oType As Type = oProxy.GetType
Dim oMeth As MethodInfo = oType.GetMethod("GetData")
Dim params() As Object = {3}
Dim sResults As String
sResults = oMeth.Invoke(oProxy, BindingFlags.Public Or BindingFlags.InvokeMethod, Nothing, params, System.Globalization.CultureInfo.CurrentCulture)
这篇关于使用反射调用 WCF 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!