Search code examples
asp.net-mvcdependency-injectionninjectcustom-model-binderrepository-design

Dependency Inject for models


I'm sure someone has asked this before, but I'm struggling to find where.

I'm using Ninject to remove dependencies from my controllers, along with a repository design pattern.

As I understand it, one of the benefits of this approach is that I can easily whip apart my repositories and domain entities and use another assembly should I so wish. Consequently I've kept my domain entities and repositories in external assemblies and can mock all my dependencies from interfaces.

It seems that while I can use interfaces to refer to my domain entities in most places I must use references to my concrete classes when it comes to model binding. I've read that this is to do with serialization which I understand, but is the only way to avoid referring to domain entities to create separate models?

Anything I can do with Custom Model Binding?

A bit of background: I'm an experienced ASP.net developer, but new to MVC.


Solution

  • The major advantage of using a dependency injection framework is IoC (Inversion of Control):

    • loosely coupling
    • more flexibility
    • easier testing

    So what one usually does is to inject repositories through their interfaces like

    public class MyController : Controller
    {
        private IPersonRepository personRepo;
    
        public MyController(IPersonRepository personRepo)
        { 
            this.personRepo = personRepo;
        }
        ...
    }
    

    During testing this allows to easily inject my mock repository which returns exactly those values I want to test.

    Injecting domain entities doesn't make that much sense as they are more tightly linked with the functionality in the specific class/controller and thus abstracting them further would just be an overhead rather than being a benefit. Instead, if you want to decouple your actual entity model from the controller you might take a look at the MVVM pattern, creating specialized "ViewModels".

    Just think in terms of testability of your controller: "What would I want to mock out to unit test it?"

    • DB accesses -> the repository
    • External dependencies -> other BL classes, WS calls etc.

    I wouldn't include domain entities here as they're normally just a data container.