In Domain-Driven Design, can you use your domain entities in your UI?

前端 未结 6 1735
野性不改
野性不改 2021-02-20 00:03

In many leading DDD projects, especially MVC style, I see the UI using display objects that mirror domain entities, rather than using those domain objects directly. This style

6条回答
  •  你的背包
    2021-02-20 00:10

    I didn't really start to understand why or how you would decouple the domain model from presentation concerns until I started following the work of Greg Young and Udi Dahan (via Martin Fowler).

    They have been teaching a principle known as Command and Query Responsibility Segregation (CQRS).

    My interpretation of CQRS is that there are two sets of responsibilities that can pull a domain model in different directions, resulting in a model that does a mediocre job of both. The two responsibilities are commands (i.e. behavior that would cause a write to the database) and queries (i.e. reading from the database in order to fetch data for UI consumption). An example would be adding getters and setters to your entities to support databinding in the UI. If your model has getters and setters, it will probably do a poor job of modeling state changes that need to happen transactionally or encapsulating business logic. It will also have no way of modeling the business context of state changes (see Event Sourcing).

    In DDD terms, you might say that the domain model and the presentation model are usually in separate Bounded Contexts.

    The solution as prescribed by CQRS is to create one model for commands and another for queries. If your current model has methods for changing state (i.e. the behavior in the model), and getters that expose state to a UI for databinding, you would refactor these two responsibilities into separate models for commands and queries. The query model will not be mapped to your domain entities, but instead directly to the database. If your database doesn't capture derived state from your domain model, check out a pattern called Eager Read Derivation.

    If your system is simply CRUD and has no behavior, try out a scaffolding system that can be automatically built off of your database schema, like ASP.NET Dynamic Data

提交回复
热议问题