2013-12-17 48 views
1

通常我會實例化一個像這樣的SoapClient的:創建通用的SOAPClient實例

public static TestWSSoapClient Test() 
{ 
    string endpoint = "endpoint"; 
    var soapClient = new TestWSSoapClient(endpoint); 

    return soapClient; 
} 

,但我想用一個更通用的方法:

public static ICommunicationObject SoapClient<TSoap>() 
{ 
    string endpoint = "endpoint"; 
    var soapClient = new TSoap(endpoint); 

    return soapClient; 
} 

但顯然你不能創建一個實例就像通用類型那樣。我怎樣才能創建這個實例,並仍然通過endpoint字符串呢?

+0

是否所有的TSoaps都有一個共同的基類? – nvoigt

+0

@nvoigt不是自定義的基類。但它們都具有'ClientBase '這是服務引用生成的默認基類。我認爲我需要對這個類做些什麼,因爲那是一個期望帶有參數的構造函數。 – w00

+0

http://stackoverflow.com/questions/2451336/how-to-pass-parameters-to-activator-createinstancet重複? –

回答

1
public static T GetChannel<T>(Binding binding, EndpointAddress address) 
{ 
    var channelFactory = new ChannelFactory<T>(binding, address); 
    var channel = channelFactory.CreateChannel(); 

    return channel; 
} 

var binding = BindingFactory.GetBindingX(); 
var address = new EndpointAddress("endpoint"); 

Program.GetChannel<IMyInterface>(binding, address); 

channel.DoStuff(parameters);