[英]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. 我正在为第三方Web服务(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.
我想以一种这样的方式来抽象代码与API的交互:如果业务关系发生变化,我可以删除对第三方API的引用。 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. 我想要做的是将我的函数
ConvertToAPIImplementation
放入一个转换器中,该转换器会将我的域对象转换为我们正在使用的期望API的类型。 How should I implement this? 我应该如何实施呢?
This is a very simple and common scenario. 这是一个非常简单且常见的场景。 Reference GoF patterns Adapter, Abstract Factory and Proxy.
参考GoF模式适配器,抽象工厂和代理。
[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. 您需要定义自己的API(或抽象接口),以表示任何第三方API需要提供给您的应用程序的功能。
IPancakeMaker
{
Pancake MakePancake(decimal radius);
}
Then write a Provider that implements that interface and depends on your current 3rd party API... 然后编写一个实现该接口并取决于您当前的第三方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. 使用流行的DI框架,例如Unity或StructureMap。
http://unity.codeplex.com/ http://unity.codeplex.com/
http://structuremap.net/structuremap/ http://structuremap.net/structuremap/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.