在 WCF 中的域层和服务层之间传输用户类型 - 建议的方法?
这个问题很熟悉 - 当通过服务边界编组用户定义/域类型时,我们是否简单地使用 [DataContract]
属性注释丰富的域对象(从而用 ServiceModel 构造污染域),或者我们是否实现一些某种 DTO 流程(创造额外的工作却几乎没有什么好处)?
- 人们如何解决这一冲突?还有其他缺点较少的方法吗?
- 如果您使用 DTO 方法,那么如何实现从域对象到 DTO 的属性值传输?
谢谢
The problem is familiar - when marshalling user defined / domain types through service boundaries, do we simply annotate rich domain objects with [DataContract]
attributes (thereby polluting the domain with ServiceModel constructs), or do we implement some sort of DTO process (creating extra work for arguably little benefit)?
- How are people resolving this conflict? Are there other approaches that have fewer downsides?
- If you're using the DTO approach, how do you go about implementing the transfer of property values from domain object to DTO?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您已经基本回答了您的问题。如果你想要非常清晰的设计使用DTO。如果您不想添加额外的复杂性,请使用
DataContract
/DataMember
属性标记类,或者使用默认序列化(仅限 .NET3.5 及更高版本),这会占用所有内容公共属性(带有 getter 和 setter) + 您可以使用IgnoreDataMember
属性从序列化中删除一些属性。要将域对象映射到 DTO,以及将 DTO 映射到域对象,您可以使用 AutoMapper。You have mostly answered your questions. If you want very clear design use DTO. If you don't want to add additional layer of complexity either mark classes with
DataContract
/DataMember
attributes or use defalut serialization (only .NET3.5 and newer) which takes all public properties (with getter and setter) + you can remove some properties from serialization by usingIgnoreDataMember
attribute. To map domain objects to DTOs and DTOs to domain objects you can use AutoMapper.如果您使用 DTO(我的建议),您可以使用汇编器模式将信息从 DTO 传输到实体,反之亦然。您可以手动完成,也可以使用工具。 AutoMapper 是一个很好的建议。
If you use DTO (my suggestion), you can transfer information from DTOs to entities and vice versa using the assembler pattern. You can do it manually or you can use tools. AutoMapper is a good suggestion.
这可能是显而易见的,但我想补充一下拉迪斯拉夫所说的内容。正如他提到的,您可以使用 POCO 类型,但您还可以灵活地使用 IXmlSerialized、ISerialized、Serializable 等;这些其他序列化模型不具有与 IgnoreDataMember 一起使用的灵活性。
请参阅此博文 了解更多信息。它还详细说明了 DataContractSerializer 如何对同一类型的两个冲突的编程模型进行优先级排序。
This may be obvious, but I want to add to what Ladislav has said. Like he mentions, you can use POCO types, but you also have the flexibility to go beyond and use IXmlSerializable, ISerializable, Serializable, and more; these other serialization moels do not have the flexibility of being used with IgnoreDataMember.
See this blog post for more information. It also details how DataContractSerializer would prioritize two conflicting programming models on the same type.