2012-01-02 26 views
1

我必須致電ChannelFactory<TChannel>班。但下面的代碼適用於ChannelFactory類。我沒有任何想法,如何撥打ChannelFactory<TChannel>。請建議我怎麼稱呼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; 

回答

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創造型槽式反射
  • 你應該完全限定你的界面名稱,以確保反射可以找到它
  • 裝飾你的服務在terface用的ServiceContract
  • 確保您的端點是有效的格式
2

好了,你有2個問題在這裏,動態創建的ChannelFactory和動態調用它,反思是對他們倆的解決方案。

您的代碼和Wouter的代碼都擅長通過反射動態創建ChannelFactory對象,問題是由於在編譯時未知類型,您無法投射到它,並且您只能獲得非通用(無用)ChannelFactory。

因此,要創建具體的Channel,然後調用其上的方法,您可以使用Reflection再次進行很長的一步......或者讓運行時本身通過動態方式代表您使用Reflection。無需

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

dynamic factory = Activator.CreateInstance(... 

包括「爲的ChannelFactory」的結尾:也就是說,你上次(或沃特的最後)行更改。

,然後只用:

dynamic channel = factory.CreateChannel(); 
//and now invoke the methods in your Interface 
channel.TestMethod...