我必须调用 ChannelFactory<TChannel>类(class)。但下面的代码适用于 ChannelFactory类(class)。我不知道如何调用 ChannelFactory<TChannel> .请建议我如何调用 ChannelFactory<TChannel>类。
string interfaceName = "Test";
Type myInterfaceType = Type.GetType(interfaceName);
var factoryType = typeof(ChannelFactory<>).MakeGenericType(myInterfaceType);
var factoryCtr = factoryType.GetConstructor(new[] { typeof(BasicHttpBinding), typeof(EndpointAddress) });
ChannelFactory factorry = factoryCtr.Invoke(new object[] { new BasicHttpBinding(), new EndpointAddress(cmbpath.SelectedItem.ToString()) }) as ChannelFactory;
请您参考如下方法:
在控制台应用程序中尝试以下代码:
using System;
using System.ServiceModel;
namespace ExperimentConsoleApp
{
class Program
{
static void Main()
{
string endPoint = "http://localhost/service.svc";
string interfaceName = "ExperimentConsoleApp.ITest";
Type myInterfaceType = Type.GetType(interfaceName);
var factoryType = typeof(ChannelFactory<>).MakeGenericType(myInterfaceType);
ChannelFactory factory = Activator.CreateInstance(factoryType, new object[] { new BasicHttpBinding(), new EndpointAddress(endPoint) }) as ChannelFactory;
}
}
[ServiceContract]
public interface ITest
{ }
}
几点:
- 使用 Activator.CreateInstance 通过反射创建类型
- 您应该完全限定您的 interfaceName 以确保反射可以找到它
- 用 ServiceContract 装饰你的服务接口(interface)
- 确保您的端点格式有效
