What are some MVC best practices

Best Practices for MVC Architecture [closed]


My question is more about the architecture of an MVC application. For example, it is recommended to use DI with the repository pattern to decouple data access from the controller. However, very little is said about how to do this specifically for MVC. For example, where would we put the repository classes? They do not seem to be model-specific, as the model should also be relatively decoupled from the actual data access technologies.

A second question concerns the structuring of the levels or layers. Most of the sample applications (nerd dinner, music store, etc) all seem to use a one-step, 2-level approach (without counting tests) where controllers usually call L2S or EF code directly.

If I want to build a multi-tier / layer application, what are the best practices for MVC?

Reply:


DI is run in ASP MVC using a controller factory. This factory is used to resolve your controller dependencies.

MvcContrib has some Controller Facotry implementations that you can use right out of the box. I'm using their Castle Windsor implementation and it works fine. I would also suggest checking out their TestHelper class. It has some very cool functions for mocking Controller HTTPContext, Sessions, etc. MVCContrib

Personally, I want to give my models a repository instance to work with. The model exposes an API to the repository (CRUD). The controller's dependency on a specific model is injected when it is created (constructor). This is injected via the controller factory. This is my entry point into the object diagram managed by my IoC container.


For example, where would we put the repository classes?

They belong in the model; They are the in-application model.

How do I structure the levels? If I want to build a multi-tier / layer application, what are the best practices for MVC?

Layers represent physical code separations. Layers represent logical separations. The layers (as they currently are) work fine for MVC. Depending on the scope of the business logic, this can either be placed in your controller or in a separate assembly and used by the controller during the request cycle.





We use cookies and other tracking technologies to improve your browsing experience on our website, to show you personalized content and targeted ads, to analyze our website traffic, and to understand where our visitors are coming from.

By continuing, you consent to our use of cookies and other tracking technologies and affirm you're at least 16 years old or have consent from a parent or guardian.

You can read details in our Cookie policy and Privacy policy.