我正在使用带有一组 WCF 服务的 DI 模式,并且 Unity 充当我的 IoC 容器。我已经完成了从服务开始的单元和功能测试,一切都按我的预期运行。我现在正在测试端点本身,并且在序列化结果时遇到了问题。
我的服务看起来像这样:
public class ProcessingService : IProcessingService
{
private IOrderService orderService;
public ProcessingService(IOrderService orderService)
{
this.orderService = orderService;
}
[WebInvoke(Method = "Get", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public IOrder CreateNewOrder(string venNum, OrderType orderType, string orderDescription, string createdBy)
{
return orderService.CreateNewOrder(venNum, orderType, orderDescription, createdBy);
}
}
orderService.CreateNewOrder
最终返回一个与此类似的复杂对象
internal partial class Order : IOrder
{
[DataMember]
public int VenNum { get; set; }
[DataMember]
public string Description { get; set; }
[DataMember]
public IList<string> RuntimeErrorMessages { get; set; }
[DataMember]
public IList<IOrderDetail> OrderDetails { get; set; }
}
这会生成异常:
"
<type>
is not expected. Consider using a DataContractResolver or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to DataContractSerializer."
此错误是有道理的,因为您不可能序列化或反序列化接口(interface)。此外,我可以通过将服务方法的返回类型更改为
来消除此错误public Order CreateNewOrder(...)
但我不想暴露我的具体对象,所以我在这里陷入了僵局。过去我记得使用 Json.Net 的 JsonConverter 类来序列化和反序列化对象,虽然当时我没有使用 DI,而且它更容易一些。那么,如何在不暴露具体类型的情况下序列化我的复杂类型呢?异常(exception)提到使用 DataContractSerializer,但似乎我必须为我想要返回的每个复杂类型编写一个序列化器,而这是不切实际的。
非常感谢您的建议!
最佳答案
减少耦合的愿望值得称赞,但是 at the boundary, an application is no longer object-oriented 。特别是对于 WCF 应用程序,边界是由 XSD 和 WSDL 定义的,因此通过网络传输的数据不再是对象,而是 XML(或者至少是 XML 信息集)。该数据没有任何行为。
SOAP 服务与其客户端之间的耦合是由契约定义的;即 WSDL。即使您可以在实现中返回接口(interface),它仍然会作为 XML 通过网络传输,因此不会有任何区别。
关于c# - WCF、依赖注入(inject)和序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33395175/