简体   繁体   中英

How to setup architecture for mvc project

I am trying to get my hands on MVC. I am from ASP.Net background.

After creating new mvc 3 application, i got Controller, Models and views under the same webapp project. In ASP.Net, we generally create separate projects for Models and Controllers (which i assume are same as Business Layer). Also i created a separate project for DAL where i will be using EF.

I am confused as is this the ideal solution structure? Should we not create separate projects for each layer? Since i created DAL as a separate project, i had to put a reference of WebApp in it because i wanted to return Model from the DAL and because of that now i am not able to add a reference of DAL to my WebApp.

Can someone please throw some light on what am i missing here? Am i not doing it right?

MVC really leaves the "M" part up to the developer.

Even in their official examples you'll see variations. Your question exposes one of the most common misconceptions about MVC. You should NOT bind your domain or data models directly to views, nor should your controller methods accept them as parameters. See this post on over and under-posting .

Ideally, your controllers will call out to a DAL, and some mechanism will map those Data or Domain models to View models. It is those View models - models that exist specifically to facilitate the UI - that should exist in the WebApp "Models" folder.

So, you were definitely on the right track creating a new assembly to contain your DAL. One of the "easiest" mechanisms for mapping to a ViewModel is a simple method on each ViewModel:

public class MyWidgetFormModel()
{
   public string Name { get; set; }
   public string Price { get; set; }

   public MapFromDAL(DAL.Widget widget)
   {
      this.Name = widget.Name;
      this.Price = widget.Price;
   }
}

Update : based on your comments, here is an excellent answer about one user's project layout.

When I started with MVC i followed the Jeffrey Palermo onion architecture. You can read about it :

here : http://jeffreypalermo.com/blog/the-onion-architecture-part-1/

here : http://jeffreypalermo.com/blog/the-onion-architecture-part-2/

and here : http://jeffreypalermo.com/blog/the-onion-architecture-part-3/

It's using a IoC support for decoupling services. I think that you should consider usage of IoC containers because the MVC architecture was thought around patterns using IoC in order to decouple services (layers).

You can also dowload a working sample from http://codecampserver.codeplex.com/ using onion architecture.

It's not the only architecture you can use with MVC but it's a very good place to start and to learn about IoC and decoupling in MVC applications.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM