具有自动生成的Web服务客户端的DI [英] DI with auto-generated web service clients

查看:70
本文介绍了具有自动生成的Web服务客户端的DI的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在整个应用程序层进行依赖项注入,并且遇到了我确定其他人已经看到的情况。我们使用了一些第三方Web服务,并且客户端是使用基类自动生成的。客户端没有接口,数据类型在同一个文件/项目中。

I'm trying to do dependency injection throughout the app tier and am running into a scenario I'm sure others have seen. There are some 3rd party web services that we consume and the clients were auto-generated with a base class. The clients do not have an interface and the data types are in the same file/project.

明显的问题是,如果我想进行单元测试,则需要模拟服务。我需要提取一个界面并将数据类型移到一个合同项目中,该项目对真实/模拟客户端均可用。但是,下次自动生成客户端时,需要重做工作。在运行时创建代理不会有太大帮助,因为那样我们就必须从WSDL中手动创建接口和数据类型。有没有更好的方法来解决这个问题?

The obvious problem is if I want to do unit testing I'll need to mock the service. I'll need to extract an interface and move the data types into a "contracts" project that is available to both real/mock clients. However, the next time the client is auto-generated that work needs to be redone. Creating a proxy at runtime wouldn't help much because then we would have to manually create the interfaces and data types from the WSDL. Is there a better way to handle this?

推荐答案

从实现中提取接口对您没有任何帮助,因为

Extracting an interface from the implementation is not going to help you much anyway, as it's going to be a poor abstraction.

接口应该由使用接口的客户端定义和拥有。正如敏捷原则,模式和实践所述,客户[...]拥有抽象接口 (第11章)。因此,任何定义以数据为中心的接口(例如从自动生成的Web服务客户端提取接口)的尝试都会迟早会引起问题,因为它违反了各种SOLID原理,例如依赖倒置原理或接口隔离原理。

Interfaces should be defined and owned by the clients that consume the interfaces. As Agile Principles, Patterns, and Practices explain, "clients […] own the abstract interfaces" (chapter 11). Thus, any attempt to define a data-centric interface like extracting interfaces from auto-generated web service clients is bound to cause problems sooner or later, because it's violating various SOLID principles like the Dependency Inversion Principle or the Interface Segregation Principle.

相反,您的客户端代码应该定义它们所需的接口。然后,您始终可以与自动生成的Web服务客户端实现那些接口。如果您使用过Microsoft的工具(Visual Studio,wsdl.exe等),则相关的自动生成类应该已经是 partial class ,这意味着您应该能够向其中添加行为而无需触摸它的自动生成部分。

Instead, your client code should define the interfaces that they require. Then you can always implement those interfaces with the auto-generated web service clients. If you've used Microsoft's tooling (Visual Studio, wsdl.exe, etc.) the relevant auto-generated class should already be a partial class, which means you should be able to add behaviour to it without touching the auto-generated part of it.

这篇关于具有自动生成的Web服务客户端的DI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆