Data Annotations and MVC 1:1 ViewModel
When developing in ASP.NET MVC I use a 1:1 ViewModel set开发者_JAVA技巧up where the viewmodel contains only the data required by the view. I'm also using data annotations to validate on the viewmodel.
My concern is that this is not following the DRY principle as I find myself having to duplicate validation throughout my sites. I'd love to have validation in one place (my domain model) but because I never send the domain model to the view model this is not possible.
I was wondering if anyone else has ran into this issue and found a suitable method of working around it or has a better solution?
We had similar concerns when we adopted a 1:1 ViewModel approach. We found that 1) the duplication is less than appears at first and 2) that the overall maintainability and power of the application is improved enough that any non-DRY costs are worth the price.
We ended up thinking about validation for the ViewModel and domain models from different perspectives (separation of concerns). When implementing validation at the domain level model we're looking for comprehensive security to prevent attacks. We're also detecting serious "contract" violations that indicate bugs in the upper layers. When implementing validation at the view model we're strictly concerned with usability.
If you approach the models from these different perspectives, there's less overlap then you might think. The domain layer might allow certain operations that you want to restrict in the ViewModel for usability reasons. Or the ViewModel might assume that only inputs for the rendered view are posted, relying on the domain model for comprehensive security validation designed to prevent attacks.
1:1 ViewModels also greatly ease testability. Tests for the ViewModel can be written independently of the domain layer which makes unit tests lighter, more maintainable and in general more useful. Likewise, you can test the domain model without the mental contortions of how inputs flow through the user interface. This also adheres to the "defense in depth" security principle.
We've also noticed that Views change much more frequently than the domain layer. There's a comfort in knowing that you've got really good security unit test coverage on your domain model and when you implement a new View, you only need to worry about validation from a usability perspective.
Lastly, if you anticipate having a web services layer, you'll find the separation of domain and view models pays dividends. Without it, the domain model inevitably gets written to support the UI. When you layer on the service interface you'll find there's an impedance mismatch.
If there does end up being significant duplication, you can always factor the validation out separately. In our experience, that hasn't been worth it for all the reasons discussed above.
精彩评论