Search code examples
asp.net-mvc-3interfacedependency-injectionmodel-bindingloose-coupling

MVC 3 passing entity as an Interface


I'm currently working on an MVC 3 project using Ninject as my DI, the business objects are stored in a separate assembly. I'm running into an issue with the controller parameters, when posting back for CRUD operations I'm getting the error "Cannot create an instance of an interface". I am aware that you can't create an instance of an interface, but it seems like the only way I can get around this is to use a custom model binder and pass the FormCollection through. This seems really messy and I want to keep as much type specific code out of the project as I can - hence interfaces everywhere and Ninject to DI the concretes. Not only does custom model binding seem messy - won't I also lose my DataAnnotations?

Some code to describe what I have:

public ActionResult Create()
{
    // I'm thinking of using a factory pattern for this part
    var objectToCreate = new ConcereteType();
    return (objectToEdit);
}

[HttpPost]
public ActionResult Create(IRecord record)
{
    // check model and pass to repository
    if (ModelState.IsValue)
    {
        _repository.Create(record);
        return View();
    }

    return View(record);
}

Has anyone run into this before? How did you get over it?

Thanks!


Solution

  • Data passed to controllers action are simply holders for values. There shouldn't be any logic in them so there is nothing to decouple from. You can use concrete types (e.g Record) instead of interface (IRecord)