Question

I am using the following code in my WCF service to call another web service which may or may not be a WCF service.

 ChannelFactory<IService1> myChannelFactory = new ChannelFactory<IService1>
                                                  (myBinding, myEndpoint);

So I want to have some information in a xml file from which i read the various services endpoints and want to pass the binding information to the channel factory and call the other services based on the information i have in the config XML file.

So i want to generate the channel factory dynamically using different service contract information every time.

Is it possible in channel factory since various services have different Interfaces?

In other words from the code above I have IService1 but when i read another service information from an xml file I want to create a channel with another Interface?

Was it helpful?

Solution

Yes, it is possible through Generics:

public static T CreateProxyChannel<T>()
{
    string endpointUri = GetServiceEndpoint(typeof(T));

    ChannelFactory<T> factory = new ChannelFactory<T>(myBinding, new EndpointAddress(new Uri(endpointUri)));

    return factory.CreateChannel();
}

And the GetServiceEndpoint method to return the endpoint based on the type of T:

private static string GetServiceEndpoint(Type service)
{
    string serviceTypeName = service.Name;

    // Code to get and return the endpoint for this service type
}

Note that in this case, I expect the config file to have an endpoint associated with the service type name (e.g. IService1 and http://localhost/Service1.svc).

And finally to use it:

IService1 serviceProxy1 = CreateProxyChannel<IService1>();
serviceProxy1.MyMethod();

IService2 serviceProxy2 = CreateProxyChannel<IService2>();
serviceProxy2.AnotherMethod();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top