我正在(重新)设计大型应用程序,我们使用基于DDD的多层架构。
我们有带有数据层(存储库的实现)、领域层(域模型和接口的定义——存储库、服务、工作单元)、服务层(服务的实现)的MVC。到目前为止,我们在所有层上使用域模型(主要是实体),并且仅将dto用作视图模型(在控制器中,服务返回域模型,控制器创建视图模型,并将其传递给视图)。
I'v read countless articles about using, not using, mapping and passing DTOs. I understand that there's no any definitive answer, but I'm not sure if it's ok or not returning domain models from services to controllers. If I return domain model, it's still never passed to the view, since controller always creates view-specific view model - in this case, it seem legit. On the other hand, it doesn't feel right when domain model leaves business layer (service layer). Sometimes service needs to return data object that wasn't defined in the domain and then we either have to add new object to the domain that isn't mapped, or create POCO object (this is ugly, since some services return domain models, some effectively return DTOs).
The question is - if we strictly use view models, is it ok to return domain models all the way to controllers, or should we always use DTOs for communication with service layer? If so, is it ok to adjust domain models based on what services need? (Frankly I don't think so, since services should consume what domain has.) If we should strictly stick to DTOs, should they be defined in service layer? (I think so.) Sometimes it's clear that we should use DTOs (e.g., when service performs lot of business logic and creates new objects), sometimes it's clear that we should use just domain models (e.g., when Membership service returns anemic User(s) - it seems it wouldn't make much sense to create DTO that is the same as domain model) - but I prefer consistency and good practices.
文章域vs DTO vs ViewModel -如何以及何时使用它们?(以及其他一些文章)与我的问题非常相似,但它没有回答这个问题。我应该用EF在存储库模式中实现dto吗?也类似,但它不处理DDD。
免责声明:我不打算仅仅因为任何设计模式的存在而使用它,另一方面,我想使用好的设计模式和实践,因为它有助于设计应用程序作为一个整体,有助于分离关注点,即使使用特定的模式不是“必要的”,至少目前是这样。