问题
Let's assume we have an ASP.NET MVC web application with following tiers:
- Business logic
- Entities (business domain and database POCOs)
- Common (resources, consts)
- Data access (database EF queries, EDMX EF models and so on)
- Web application (MVC web application)
We're using view models approach. Currently view models are placed in Entities layer. Data access queries returns view models (due to efficiency issues, so we avoid using mapper).
Web layer references all other layers. Data access references Common and Entities layers. Business logic references Entities and Common layers, in the future also Data access layer.
There's an idea to move view models to Web layer. Why? Because they're in fact bound with a particular technology (MVC) and UI implementation. But we're facing a problem here, because in this scenario Data access layer must reference Web and Web references Data access, so we have a circular dependency issue.
Moreover we have scenario when some validation of view model requires reference to Data access layer. We're going to keep validation method inside view models. Currently we want to implement it by injecting database context class (which is in Data access layer) to view model by constructor.
Do you have any idea how can we avoid it? Is it good idea to keep view models inside our Web layer?
回答1:
I'm unsure how you can use ViewModel
in web apps. AFAIK it's harder than in desktop app due to it's data-binding nature.
However, your web layer referenced directly to data layer (or rather, access directly). Unless it is used to help simplify the UI and not the business process, it is breaking the purpose of N-tier aswell.
What you need to do to keep the design clean is making 2 different model. One for Entities model (Domain/data/business model) and another for view model. Your view model is placed at web layer and when received the domain model, it is being mapped to web layer. You cannot avoid mapping here.
来源:https://stackoverflow.com/questions/29431357/where-view-models-inside-web-project-of-n-tier-application-should-be-placed