Reputation: 11319
I'm writing a wrapper class for a third-party web service(SOAP) api. I want to abstract my code's interaction with the API in such a way that I can remove the reference to the third party API if the business relationship changes. Consider the following code:
public Tapitype ConvertToAPIImplementation<Tapitype>(APIConverter domainToApiConverter){
return domainToApiConverter.ConvertToAPIObject(this);
}
What I want to do is have my function ConvertToAPIImplementation
take in a converter that will convert my domain object into the type the desired API we are using expects. How should I implement this?
Upvotes: 0
Views: 422
Reputation: 3999
This is a very simple and common scenario. Reference GoF patterns Adapter, Abstract Factory and Proxy.
[EDIT: Added more code to help illustrate solution]
You need to define your own API (or abstraction interface) that represents the functionality that any 3rd party API needs to provide to your application.
IPancakeMaker
{
Pancake MakePancake(decimal radius);
}
Then write a Provider that implements that interface and depends on your current 3rd party API...
WalmartPancakeMaker : IPancakeMaker
{
Walmart3rdPartyAPI _w3paPancakeMaker = new Walmart3rdPartyAPI(string apiKey);
// ... set 3rd party settings, defaults, etc
// Implement IPancakeMaker
public Pancake MakePankcake(decimal radius)
{
Walmart3rdPartyPancakeEntity thirdPartyPancake = _w3paPancakeMaker.BakeMeACakeJustAsFastAsYouCan(radius);
return this.ConvertToPancakeInMyDomain(thirdPartyPancake);
}
}
Create a service class (or some other orchestration) to control interaction with your provider and use Dependency Injection to avoid tight coupling to the Provider...
public class MakePancakesService
{
IPancakeMaker _pancakeMaker = null;
// Constructor takes the concrete Provider of IPancakeMaker
// Your calling code is not aware of the actual underlying API
public MakePancakesService(IPancakeMaker pancakeMaker)
{
_pancakeMaker = pancakeMaker;
}
}
Use a popular DI framework such as Unity or StructureMap.
http://structuremap.net/structuremap/
Upvotes: 1