简体   繁体   中英

How to build a generic wrapper to decouple domain objects from a specific API?

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?

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://unity.codeplex.com/

http://structuremap.net/structuremap/

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