Search code examples
c#asp.net-mvc-3dependency-injectionninject-2

Get instance of objects based on other values without using service location


I am using a Unit of Work pattern in my mvc 3 app with Ninject. I have run into a problem where i'm having difficulty solving it without using new or service location of some kind.

I am using an abstract base model called MyModel which has 2 concrete subclasses MyModel1 and MyModel2. These need to get sent to the view based on a value set in the users record.

public class MyController : Controller
{
    private IUnitOfWork _unitOfWork;
    public MyController(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; }

    ...

    public ActionResult MyMethod() {
        var user = _unitOfWork.Get(user)

        if (user.myprop == somevalue)
        {
            return View(new MyModel1());
        }

        return View(new MyModel2());
    }

This works fine (although I don't like it, it's simple and works. The problem is that using new is an anti-pattern when using Dependancy Injection. Additionally, I now want the models to initialize themselves (from the database) so I need to inject the IUnitOfWork into the constructor of the models. I could, of course do this:

if (user.myprop == somevalue)
{
    return View(DependancyResolver.Current.GetService(typeof(MyModel1)));
}

But Service Location is also an anti-pattern.

Any suggestions on how to solve this?


Solution

  • Using new is not an anti pattern for DI if used correctly. There is absolutely no problem to use new to create data containers such as view models.

    But it is an anti pattern for MVC applications to have logic or data retrieving code in your view models so that they need dependencies. All this stuff belongs outside into the controller or some services. The data is assigned preformatted to the view model from outside.