Given my understanding of MVC and DDD (critique as necessary):
- Domain Models can be created by Factories, and persisted by Repositories. These are POCO objects.
- View Models contain partial or complete Domain Models as needed by the view. They are generated by a service that interacts with a repository. Thus Domain Models never make it to the view directly. Likewise, ViewModels are never persisted.
- You will very likely have multiple View Models for the same Domain Model because you开发者_JAVA技巧 could show it on multiple views.
That said, adding data validation to the Domain Model removes any kind of redundancy.
So how do you get the ViewModels to inherit the Domain Model data validation?
I wouldn't expect simply referencing a Domain Model from a View Model to work.
I asked this same question at the patterns & practices summit last October while speaking to Brad Wilson and he did not have a global solution.
One idea I discussed with him was extending an object mapping library such as AutoMapper to also map validation from the domain model to the view model.
In designing a framework to facilitate this scenario, some things to consider:
Validation rules may depend on the context and thus may be unique to the particular view model. The Enterprise Library Validation Block allows the setup of validation logic using a configuration file - this for example, could be extended to transfer to view models as well.
The View Model could have properties which are not part of the domain model, such as a property that specified that a certain "agree to terms" checkbox has been checked. This property requires validation however it is specific to the view and use case, not the domain model. This scenario serves as another argument to keep the validation logic separate, at least partially.
For the purposes of maintenance and clarity it may be easier to duplicate certain validation logic for the domain model and view model instead of using a mapping framework.
精彩评论