【问题标题】:How do I call ChannelFactory<TChannel> dynamically?如何动态调用 ChannelFactory<TChannel>?
【发布时间】:2012-01-02 11:46:50
【问题描述】:

我必须打电话给ChannelFactory&lt;TChannel&gt; 上课。但是下面的代码是针对ChannelFactory 类的。我不知道如何打电话给ChannelFactory&lt;TChannel&gt;。请建议我如何称呼ChannelFactory&lt;TChannel&gt; 类。

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;

【问题讨论】:

    标签: c# channelfactory


    【解决方案1】:

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

    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 装饰您的服务接口
    • 确保您的端点采用有效格式

    【讨论】:

      【解决方案2】:

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

      您的代码和 Wouter 的代码都擅长通过 Reflection 动态创建 ChannelFactory 对象,问题是由于在编译时类型未知,您无法对其进行强制转换,而您只能得到非泛型 (无用)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...
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-28
        • 2011-01-01
        相关资源
        最近更新 更多