advice on architecting asp.net mvc applications

2019-03-30 05:46发布

问题:

I've been using ASP.net MVC for about two years now and I'm still learning the best way to structure an application.

I wanted to throw out these ideas that I've gathered and see if they are "acceptable" ways in the community to design MVC applications.

Here is my basic layout:

  • DataAccess Project - Contains all repository classes, LINQ-to-SQL data contexts, Filters, and custom business objects for non-MS SQL db repositories (that LINQ-to-SQL doesn't create). The repositories typically only have basic CRUD for the object they're managing.

  • Service Project - Contains service classes that perform business logic. They take orders from the Controllers and tell the repositories what to do.

  • UI Project - Contains view models and some wrappers around things like the ConfigurationManager (for unit testing).

  • Main MVC Project - Contains controllers and views, along with javascript and css.

Does this seem like a good way to structure ASP.NET MVC 2 applications? Any other ideas or suggestions?

Are view models used for all output to views and input from views?

I'm leaning down the path of making view models for each business object that needs to display data in the view and making them basic classes with a bunch of properties that are all strings. This makes dealing with the views pretty easy. The service layer then needs to manage mapping properties from the view model to the business object. This is a source of some of my confusion because most of the examples I've seen on MVC/MVC2 do not use a view model unless you need something like a combo box.

If you use MVC 2's new model validation, would you then validate the viewmodel object and not have to worry about putting the validation attributes on the business objects?

How do you unit test this type of validation or should I not unit test that validation messages are returned?

Thanks!

回答1:

Interesting.

One thing I do differently is that I split off my DataAccess project from my Domain project. The domain project still contains all the interfaces for my repositories but my DataAccess project contains all the concrete implementations of them.

You don't want stuff like DataContext leaking into your domain project. Following the onion architecture your domain shouldn't have any dependencies on external infrastructure... I would consider DataAccess to have that because it's directly tied to a database.

Splitting them off means that my domain doesn't have a dependency on any ORM or database, so I can swap them out easily if need be.

Cheers,
Charles

Ps. What does your project dependency look like? I've been wondering where to put my ViewModels. Maybe a separate UI project is a good idea, but I'm not entirely sure how that would work. How do they flow through the different project tiers of your application?