Search code examples
asp.net-mvc-3model-view-controllermvvmviewmodelview-model-pattern

MVC: Repository and Viewmodels both pattern together for better structure?


If I want to combine using repositorys per entity and Viewmodels per view how does it work out?

Any website tips I could look up? Maby someone could give an easy example?

Thanks

Best Regards!


Solution

  • I like the following structure (from the famous Steven Sanderson's Pro ASP.NET MVC series):

    Domain Project (Business Logic):

    • Abstract Folder (repository interfaces)
    • Concrete Folder (repository implementations)
    • Entities (EF generated classes)

    Web UI Project (MVC Web App):

    • Models (view models)
    • Views
    • Controlers
    • etc, you get the point

    The main thing is you're separating your business logic (which should house your repositories) from your Web UI (the MVC project)

    In this scenario, your Controller classes reference the domain layer and use DI/IoC to call up the correct instance of the repository.

    Example controller class:

    namespace MyMvcProject
    {
        using System.Whatever;
        using MyDomainLayer;
    
        public class MyController : Controller
        {
            private readonly IMyRepository _myRepository;
    
            public MyController(IMyRepository myRepository)
            {
                // Resolved using your favorite DI/IoC Container:
                this._myRepository = myRepository;
            }
    
            public ActionResult DoSomething()
            {
                var stuff = _myRepository.GetStuff();
                return View(stuff);
            }
        }
    }