简体   繁体   中英

Replaceable 3rd party services

We are refactoring and upgrading a system that heavily relies on 3rd party integrated services. The problem is that client changes the service providers quite frequently, for example swithes from one SMS service provider to another. Each provider has different API's with different parameteres and methods, what is the best way to make switching less painfull?

We've already tried to create a unified interfaces for all 3rd party services, which allows to predefine a set of methods that each 3rd party service wrapper should implement, but the problem is that different services has different parameters and return values.

What we also tried is to make all methods receive a single parameter - a class implementing an interface IArgs, and then an additional adapter class that implements the ISmsService which casts the args to a required type and passes it to a service wrapper class. But there's too much overhead, as you need to create a args class per method.


// common interface
public interface ISmsService 
{
   Task<int> Send(string phoneNumber, string text);
}

//external rest service1 wrapper class
public class SmsService1 : ISmsService
{
   public int Send(string text, string phoneNumber)
   {
      //call rest endpoint here
   }
}

// external rest service 2 wrapper class
public class SmsService2
{
   public string Send(int clientId, string countryCode, string phoneNumber, string text)
   {
      //call rest endpoint here
   }
}


//actual service call
this._smsService.Send("123456789", "Hello");

//switch to
this._smsService.Send(12, "21", "123456789", "Hello");

What is the correct way of implementing such approach?

the declared field _smsService should be of type of your declared interface: ISmsService , you make your life easier by using dependency injection for instantiation.

The invoker then always calls this._smsService.Send("123456789", "Hello");

All the required parameters must be loaded by the appropriate implementation for exampe inside the constructor from a configuration. This way each wrapper has the Send method with the same signature and all provider specific parameters are hidden to the caller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM