28

My question is more about how to architect an MVC application. For example, we are encouraged to use DI with the Repository pattern to decouple data access from the controller, however very little is said on HOW to do that specifically for MVC. Where would we place the Repository classes, for instance? They don't seem to be model related specifically, since the model should likewise be relatively decoupled from the actual data access technologies.

A second question involves how to structure the layers or tiers. Most example applications (Nerd dinner, Music Store, etc..) all seem to use a single tier, 2 layer approach (not counting tests) that typically has controllers directly calling L2S or EF code.

If I want to create a multi-tier/layer application what are some of the best practices there in regards to MVC?

2 Answers2

5

DI is accomplished 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 out of the box. I use their Castle Windsor implementation and it works well. Would also suggest checking out their TestHelper Class. It has some very cool functionality for mocking Controller HTTPContext, Sessions, etc.. MVCContrib

Personally I like 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 particular model is injected on creation (constructor) this is injected via the Controller Factory. This is my entry point to the object graph which my IoC container manages.

2

Where would we place the Repository classes, for instance?

They belong in the model; they're the in-application model.

How to do I structure the layers? If I want to create a multi-tier/layer application what are some of the best practices there in regards to MVC?

Tiers Represent physical separations of code. Layers represent logical separations. The layers (as they presently are) work well for MVC. Depending on the amount of business logic, it can either be placed in your Controller, or it can be placed in a separate assembly and can be used by the controller during the request cycle.