1

我得打电话ChannelFactory<TChannel>上课。但是下面的代码是针对ChannelFactoryClass 的。我不知道如何打电话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;
4

2 回答 2

2

好吧,这里有两个问题,动态创建 ChannelFactory 并动态调用它,Reflection 是解决这两个问题的方法。

您的代码和 Wouter 的代码都擅长通过反射动态创建 ChannelFactory 对象,问题是由于在编译时类型未知,您无法转换为它,而您所能得到的只是非泛型(无用)通道工厂。

因此,要创建您的具体 Channel 并在其上调用方法,您可以自己再次使用 Reflection……或者让运行时本身通过动态方式代表您使用 Reflection。也就是说,将您的最后一行(或 Wouter 的最后一行)更改为:

dynamic factory = factoryCtr.Invoke(.....

或者

dynamic factory = Activator.CreateInstance(...

无需在末尾包含“as ChannelFactory”。

然后只需使用:

dynamic channel = factory.CreateChannel();
//and now invoke the methods in your Interface
channel.TestMethod...
于 2013-05-30T17:45:03.500 回答
2

在控制台应用程序中尝试以下代码:

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 装饰你的服务接口
  • 确保您的端点采用有效格式
于 2012-01-02T12:20:20.933 回答