Search code examples
restwcfsoapasp.net-web-api2wcf-binding

How to Consume SOAP WCF Service and REST API Together


I'm writing a very basic application and it will fetch some data from database, and will pass on this data to different web services across the country. My issue is that, the services on to which I have to pass data are WCF Services and some of them are WEB API's. I want to consume wcf service without adding service reference, so I wont be creating a separate proxy classes for all the services, because in future we will be adding further more clients and I'll be consuming their service as well, so manually adding service reference for everyone is not the solution at the moment.

I'll be using following code to consume different wcf services:

BasicHttpBinding binding = new BasicHttpBinding();
EndpointAddress address = new EndpointAddress("http://localhost:4684/Service1.svc");
ChannelFactory factory = new ChannelFactory<ServiceContract>(binding, address);
ServiceContract channel = factory.CreateChannel();
string resturnmessage = channel.YourMethod("test");

But I cannot use this method to consume REST API's, so i have to separately write a dedicated function for this, and needs to mark clients whether they have REST API or WCF Service.

Please help in this regard. thanks


Solution

  • You can put the SOAP code in a SOAPDriver class and the REST code in a RESTDriver class.

    Then create a WebService class that uses SOAPDriver or RESTDriver depending on the service it's been told to communicate with.

    pseudo code:

    // Get database data
    String data = getDatabaseData();
    
    WebService webService = new WebService();
    webService.send(WebService.REST, data); // REST and SOAP are variables in the WebService class
    
    class WebService {
      public static final int REST = 1;
      public static final int SOAP = 2;
    
      public void send(int serviceType, String data) {
        switch (serviceType) {
          case REST:
            restDriver.send(data);
            break;
            ...
        }
      }
    }