CodingIntrigue
CodingIntrigue

Reputation: 78595

Unity dependency injection for Models

I've just started using Unity with MVC and I'm running into, what I see as, a bit of code duplication. Consider the following Controller/Model pattern:

Controller:

public class MyController : Controller {
    private readonly IDependency1 _dependency1;
    private readonly IDependency2 _dependency2;
    private readonly IDependency3 _dependency3;

    public MyController(
        IDependency1 dependency1,
        IDependency2 dependency2,
        IDependency3 dependency3
    ) {

    }

    public ActionResult Thingy() {
        var model = new Thingy(_dependency1, _dependency2, _dependency3);
        model.DoLogic();
        model.SetUpView();
        model.Finalize();
        return View(model);
    }
}

Model:

public class Thingy {
    private readonly IDependency1 _dependency1;
    private readonly IDependency2 _dependency2;
    private readonly IDependency3 _dependency3;

    public Thingy(
        IDependency1 dependency1,
        IDependency2 dependency2,
        IDependency3 dependency3
    ) {

    }

    // Now I can use my dependencies
}

This allows me to implement skinny controllers/fat models, however I am now duplicating dependencies in both Controller & Model.

I saw that I can use attributes in my model:

public class Thingy {
    [Dependency]
    public IDependency1 Dependency1 { private get; set; };
    [Dependency]
    public IDependency2 Dependency2 { private get; set; };
    [Dependency]
    public IDependency3 Dependency3 { private get; set; };
}

Then initialize my model in my action like so:

public ActionResult Thingy() {
    // No need to pass in via constructor
    var model = DependencyResolver.Current.GetService<Thingy>();
}

Nice & lean from a coding POV, but I read that this is an anti-pattern?

Q: Why is this considered an anti-pattern and can I modify my structure to prevent code duplication?

Upvotes: 0

Views: 374

Answers (1)

sribin
sribin

Reputation: 1736

Yes, this is anti-pattern. One reason - excess relatedness code. If you want to replace IoC container (for example the NInject) then you have to change the code of the controller and model. It violates Open/closed principle (http://en.wikipedia.org/wiki/SOLID_(object-oriented_design)). Also, you will be hard to do unit testing controller.

Upvotes: 2

Related Questions