1

Normally i would instantiate a SoapClient like this:

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

    return soapClient;
}

But i'd like to use a more generic approach:

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

    return soapClient;
}

But obviously you cannot create an instance like that from a generic type. How can i create this instance and still pass the endpoint string to it?

w00
  • 26,172
  • 30
  • 101
  • 147
  • Do all your TSoaps have a common base class? – nvoigt Dec 17 '13 at 10:18
  • @nvoigt Not a custom base class. But they all have `ClientBase` which is a default base class that the Service Reference generates. I think i need to do something with that class though, since that is the one that expects a constructor with an argument. – w00 Dec 17 '13 at 10:22
  • http://stackoverflow.com/questions/2451336/how-to-pass-parameters-to-activator-createinstancet duplicate? – Janne Matikainen Dec 17 '13 at 10:24
  • @JanneMatikainen Almost, unfortunately it is not as easy as that. I need to create an instance of `TestSoapClient` which has an abstract base class `ClientBase`. I need to create an instance of that in a generic way. – w00 Dec 17 '13 at 10:35
  • You cant just use ChannelFactory? – Janne Matikainen Dec 17 '13 at 10:38
  • @JanneMatikainen Wow, didn't know that existed... But thanks, this is way better than what i was trying :) Can you post that as an answer so i can accept it. – w00 Dec 17 '13 at 10:48

1 Answers1

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);
Janne Matikainen
  • 5,061
  • 15
  • 21