Reputation: 11578
I'm coming from Web Api so maybe this question will be a little weird. I'm working in Visual Studio 2012
I've two WCF services
right now (but in the future will be more) that accept the same object (suppose datacontract A with same datamembers)
I'm calling them in this way:
string url1 = "myURL1";
BasicHttpBinding binding1 = new BasicHttpBinding();
EndpointAddress address1 = new EndpointAddress(url1);
ServiceClient1 serviceClient1 = new ServiceClient1(binding1, address1);
string url2 = "myURL2";
BasicHttpBinding binding2 = new BasicHttpBinding();
EndpointAddress address2 = new EndpointAddress(url2);
ServiceClient2 serviceClient2 = new ServiceClient2(binding2, address2);
It is possible call them dinamically? In one only method in order to just change the urls?
Is it possible call them without any reference of the type? Because I need use a common method in both and that method receives the same object and retrieves the same object.
Upvotes: 0
Views: 147
Reputation: 9089
T CreateServiceClient<T>(string url)
{
var binding = new BasicHttpBinding();
var endpointAddress = new EndpointAddress(url);
return (T) Activator.CreateInstance(typeof(T), new object[] {binding, endpointAddress});
}
Should be able to use it like so:
var client1 = new CreateServiceClient<ServiceClient1>("http://...");
var client2 = new CreateServiceClient<ServiceClient2>("http://...");
You can look into generics and try to constrain T
to be more specific as this doesn't give you any type safety.
If you mean dynamically like you only have a Type
, you can do this:
object CreateServiceClient(Type serviceClientType, string url)
{
var binding = new BasicHttpBinding();
var endpointAddress = new EndpointAddress(url);
return Activator.CreateInstance(serviceClientType, new object[] {binding, endpointAddress});
}
Just change object
to be a more generic interface or class that all of your clients adhere to if you have one defined.
Based on your updated question you will need to do one of two things
I highly recommend #1, but if for some reason that is not possible, you can do #2. If you need to do #2, you could meet halfway between the two and implement a wrapper class that tries to union some of this functionality:
public class MyServiceWrapper
{
Type _serviceType;
public MyServiceWrapper(Type serviceType)
{
_serviceType = serviceType;
}
public object CreateInstance()
{
... code from above ...
}
public YourObject InvokeServiceMethod()
{
var instance = CreateInstance();
var methodInfo = _serviceType.GetMethod("MethodName");
return (YourObject) methodInfo.Invoke(instance, anyArguments);
}
}
Upvotes: 1